A React hook is a function that lets you listen to the state and lifecycle events of a React component. Hooks are restricted to functional components.
React ships with a number of hooks that have different functions, such as:
useState
: represents and uses the state of a component.useEffect
: handles side effects such as network calls and manual DOM updates.useRef
: gets the A custom hook in React.js is a user-defined hook that builds on one or more default hooks. A custom hook enables you to encapsulate functionality into a reusable hook.
For example, say you want to conditionally render a component based on the window’s screen size. JavaScript lets you add a resize event listener to the window object so you can run some logic whenever a window is resized. You can create a custom hook called useScreenSize
that will detect changes in screen size and return the updated screen size.
You can structure your custom hook with the following pseudocode:
function useScreenSize() {
/**
* Represent screen size by an internal state using useState
* Update the internal state in a useEffect hook whenever the screen is resized
* Return the new screen size
*/
}
Here’s the JavaScript implementation of the pseudocode:
import { useState, useEffect } from 'react';
export function useScreenSize() {
// Represent screen size by an internal state using useState
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
// Update the internal state in a useEffect hook whenever the screen is resized
const handleResize = () => {
setSize({ width: window.innerWidth, height: window.innerHeight });
};
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
// Return the screen size
return { width: size.width, height: size.height };
}
You have to note that an event listener needs to be removed when the component that it was created in unmounts. If it isn’t removed, it may cause a memory leak, especially in an older browser like IE11. The resize
event listener is removed in the return function of the useEffect
hook above.
useState
.The code below shows how the useScreenSize
hook works. The page gets updated with the current screen size whenever the window screen is resized.
function useScreenSize() { const { width, height } = window.screen; // Represent screen size by an internal state using useState const [size, setSize] = useState({ width, height }); // Update the internal state in a useEffect hook whenever the screen is resized useEffect(() => { const { width, height } = window.screen; setSize({ width, height }); }, [window.screen]); // Return the screen size return { width: size.width, height: size.height }; } export default useScreenSize