React
Lesson 1 - Introduction
Lesson 3 - Components In React
Lesson 4 - Props
Lesson 6 - States
Lesson 7 - Conditional Rendering
Lesson 8 - Styling In React
Lesson 9 - Forms In React
Lesson 10 - `UseEffect` Hook
Lesson 11 - Web Service Calls In React
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
.