16
loading...
This website collects cookies to deliver better user experience
useWindowWidth
function, you'll notice that it's just a normal function that also happens to use other built-in hooks like useState
& useEffect
.useState
calling it width
& its setter setWidth
and throws in the value of window.screen.width
as its initial state.useEffect
hook and add an event listener for the 'resize' event firing off a function that sets the value of width
whenever the browser window is resized.useEffect
hook, you'll see an empty array which is there to indicate that this useEffect
does not depend on any external value meaning that it will ONLY RUN ONCE even in occasional re-renders. This array is also called the DEPENDENCY ARRAY of the useEffect
hook.width
value as the output of this function. Next time the browser window is resized, it will return a new value of width
representing the window's current screen width. And we know that whenever we associate useState
to a variable, it causes a re-render in every location where the variable was referenced.useWindowWidth
? "Do I have to name my custom Hooks starting with “use”? Please do. This convention is very important. Without it, we wouldn’t be able to automatically check for violations of rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it.