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
useWindowWidthUse React's
useState and useEffect hooks inside useWindowWidthAdd an event listener for the window resize event inside
useEffectReturn the current window width from
useWindowWidthCreate a functional component
WindowWidthDisplay that uses useWindowWidthDisplay 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