0
0
Reactframework~30 mins

Creating custom hooks in React - Try It Yourself

Choose your learning style9 modes available
Creating a Custom React Hook for Window Width
📖 Scenario: Imagine you want your React app to respond when the browser window size changes. This helps make your app look good on phones, tablets, and computers.
🎯 Goal: You will build a custom React hook called useWindowWidth that tracks the current width of the browser window. Then you will use this hook inside a component to show the window width on the screen.
📋 What You'll Learn
Create a custom hook named useWindowWidth
Use React's useState and useEffect hooks inside useWindowWidth
Add an event listener for the window resize event inside useEffect
Return the current window width from useWindowWidth
Create a functional component WindowWidthDisplay that uses useWindowWidth
Display the current window width inside WindowWidthDisplay
💡 Why This Matters
🌍 Real World
Custom hooks let you share logic like event listeners or data fetching across many components in React apps, making code cleaner and easier to maintain.
💼 Career
React developers often write custom hooks to handle common tasks like tracking window size, form inputs, or API calls, which is a valuable skill in frontend development jobs.
Progress0 / 4 steps
1
Set up the initial React component
Create a functional React component called WindowWidthDisplay that returns a <div> with the text "Window width will show here".
React
Need a hint?

Start by writing a simple function that returns some JSX with a div and text.

2
Create the custom hook skeleton
Create a custom hook named useWindowWidth that returns 0 for now. Add this function above WindowWidthDisplay.
React
Need a hint?

Custom hooks are functions that start with 'use'. For now, just return 0 to test.

3
Add state and effect to track window width
Inside useWindowWidth, use useState to create a state variable width initialized to window.innerWidth. Use useEffect to add a window resize event listener that updates width. Return width from the hook.
React
Need a hint?

Use useState to store width and useEffect to update it on resize. Don't forget to clean up the event listener.

4
Use the custom hook inside the component
Inside WindowWidthDisplay, call useWindowWidth to get the current width. Replace the div text with {`Window width: ${width}px`} where width is the value from the hook.
React
Need a hint?

Call your hook inside the component and use the returned width in the JSX.