javascript / intermediate
Snippet
Encapsulating Logic with Custom Hooks
Custom hooks allow you to extract component logic into reusable functions. They must start with 'use' to follow React's rules of hooks.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
function useWindowSize() {const [size, setSize] = useState(window.innerWidth);useEffect(() => {const handleResize = () => setSize(window.innerWidth);window.addEventListener('resize', handleResize);return () => window.removeEventListener('resize', handleResize);}, []);return size;}
react
Breakdown
1
function useWindowSize() {
Creates a reusable hook starting with 'use' prefix.
2
window.addEventListener('resize', handleResize);
Sets up an event listener when the component mounts.
3
return size;
Returns the state value for use in any component.