Member-only story

Re-render View Based on Browser Size with a React Custom hook

Exploring useLayoutEffect to add and remove an event listener

Kitson Broadhurst
3 min readFeb 10, 2020

Sometimes you might want to make decisions about the UI based on the size of the user’s browser. Maybe a component should be hidden or shown at different screen sizes.

Big ol’ carrot

In most cases, you’ll probably want to use media queries in your CSS to handle different screen sizes, but there are some exceptions where this isn’t sufficient.

There are libraries which offer similar functions, like useMediaQuery from Material-UI, but the simple alternative is to write a basic React hook to do the same job.

No extra libraries needed!

Writing a React Custom hook

Let’s start by asking the questions “why would I want to write a custom hook?”.

When we want to share logic between two different components, we write a shared helper function. Hooks are just functions that start with “use”.

Straight from the React docs:

Building your own Hooks lets you extract component logic into reusable functions.

useLayoutEffect vs. useEffect

--

--

Kitson Broadhurst
Kitson Broadhurst

Written by Kitson Broadhurst

Senior Web Engineer at Kin + Carta, London, working mainly with React @kit_son

No responses yet