Creating a Custom React Hook
✅ What is a Custom React Hook?
A custom hook is a JavaScript function that starts with the word use and can call other hooks (like useState, useEffect, etc.) inside it. It helps you encapsulate common logic and reuse it in multiple components.
๐งฑ Example: useWindowWidth Hook
Let’s create a custom hook that tracks the width of the browser window.
Step 1: Create the Hook
jsx
Copy
Edit
// useWindowWidth.js
import { useState, useEffect } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
// Cleanup when component unmounts
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
export default useWindowWidth;
Step 2: Use the Hook in a Component
jsx
Copy
Edit
// App.js
import React from 'react';
import useWindowWidth from './useWindowWidth';
function App() {
const width = useWindowWidth();
return (
<div>
<h1>Your screen width is: {width}px</h1>
</div>
);
}
export default App;
๐ฆ When to Use Custom Hooks
To reuse logic across components (e.g., form validation, fetch requests).
To organize code more clearly (separation of concerns).
To abstract complex logic away from UI components.
⚙️ More Examples of Custom Hooks
useLocalStorage – persist state in local storage.
usePrevious – get the previous value of a variable.
useFetch – abstract API fetching logic.
useDebounce – delay value changes for inputs or search.
๐ก Tips
Always name your hook starting with use so React knows it’s a hook.
Custom hooks can use other hooks, but not be used inside regular functions or conditionals.
Learn MERN Stack Course in Hyderabad
Read More
Building a Markdown Editor with React
Handling Forms in React with Formik
Using Tailwind CSS in a MERN Stack App
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment