Lesson 5 - Hooks

5.2 - Custom Hooks

Custom hooks allow you to create reusable hooks that encapsulate logic shared between components. They follow the same rules as React's built-in hooks and let you abstract away complex logic into reusable functions.

Custom hooks enable you to reuse the same logic in multiple components, reducing code duplication.

The following example demonstrates the use of custom hooks.

import React, { useState, useEffect }  from 'react';

function useWindowWidth() {
 const [width, setWidth] = useState(window.innerWidth);

 useEffect(() => {
 const handleResize = () => setWidth(window.innerWidth);

 window.addEventListener('resize', handleResize);
 return () => window.removeEventListener('resize', handleResize);
 }, []);

 return width;
}

function App() {
 const width = useWindowWidth();

 return (
 <>
 <p>The window width is {width}px</p>
 </>
 );
}

Notice that we created a custom hook useWindowWidth that detects the current width of the screen. Then we directly called it from our main function App. Here is how it works,

Firstly, the useState hook initializes the width state with the current window.innerWidth.

Then the useEffect hook Manages side effects, specifically adding an event listener for resizing events. When the window is resized, the handleResize function updates the width state with the new window width.

Lastly, we return the width state to the parent component App.