Custom Hooks in React
A Custom Hook is a JavaScript function that allows you to reuse stateful logic across multiple components in a React application. Custom hooks are a powerful tool for encapsulating logic that can be shared among components, keeping the components clean, and promoting code reusability.
Custom hooks are prefixed with use
, to follow React’s convention, and can use other hooks inside them (such as useState
, useEffect
, useContext
, etc.).
Why Use Custom Hooks?
Custom hooks provide several benefits:
- Code Reusability: They allow you to extract reusable logic from your components. If you have logic that needs to be shared among multiple components, you can extract it into a custom hook.
- Separation of Concerns: By moving complex logic out of components, custom hooks can help keep components more focused on rendering UI, which improves readability and maintainability.
- Abstraction: They provide a way to abstract complex logic, making your components cleaner and easier to understand.
How to Create a Custom Hook
To create a custom hook, follow these steps:
- Write a function: The function should contain the logic you want to reuse.
-
Use built-in hooks: Inside the function, you can use other React hooks such as
useState
,useEffect
, or any other hooks to manage state or side effects. - Return values: Return the necessary state, functions, or values from the custom hook to be used in the component.
Basic Example of a Custom Hook
Here is a simple example of a custom hook that manages the mouse position:
import { useState, useEffect } from 'react';
// Custom Hook to track mouse position
const useMousePosition = () => {
const [position, setPosition] = useState({ x: 0, y: 0 });
useEffect(() => {
const updatePosition = (event) => {
setPosition({ x: event.clientX, y: event.clientY });
};
// Add event listener for mouse movement
window.addEventListener('mousemove', updatePosition);
// Clean up the event listener
return () => {
window.removeEventListener('mousemove', updatePosition);
};
}, []);
return position;
};
export default useMousePosition;
Explanation:
- The custom hook
useMousePosition
tracks the mouse position on the screen. - It uses
useState
to manage the state of the mouse coordinates (x
andy
). - It uses
useEffect
to add an event listener for the mousemove event and cleans it up when the component is unmounted or the effect is re-run. - The hook returns the mouse position (
x
andy
), which can be used by any component that imports and callsuseMousePosition
.
Using the Custom Hook in a Component
Now, you can use this custom hook in any component to access the mouse position:
import React from 'react';
import useMousePosition from './useMousePosition';
const MouseTracker = () => {
const position = useMousePosition(); // Using the custom hook
return (
<div>
<h2>Mouse Position:</h2>
<p>X: {position.x}, Y: {position.y}</p>
</div>
);
};
export default MouseTracker;
Explanation:
- The
MouseTracker
component uses theuseMousePosition
custom hook to access the mouse position. - Whenever the mouse is moved, the position is updated, and the component re-renders to display the new coordinates.
Advanced Example: Custom Hook for Form Handling
You can create custom hooks for more complex logic, like form handling.
import { useState } from 'react';
// Custom Hook to handle form input
const useFormInput = (initialValue) => {
const [value, setValue] = useState(initialValue);
const handleChange = (event) => {
setValue(event.target.value);
};
return {
value,
onChange: handleChange,
};
};
export default useFormInput;
Explanation:
- The
useFormInput
hook takes an initial value and returns the input value and ahandleChange
function. - The hook can be used in any form component to manage form input state.
Using the Form Hook in a Component
Now, you can use useFormInput
in a form component:
import React from 'react';
import useFormInput from './useFormInput';
const MyForm = () => {
const nameInput = useFormInput('');
const emailInput = useFormInput('');
const handleSubmit = (event) => {
event.preventDefault();
console.log('Name:', nameInput.value);
console.log('Email:', emailInput.value);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Name:</label>
<input type="text" {...nameInput} />
</div>
<div>
<label>Email:</label>
<input type="email" {...emailInput} />
</div>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
Explanation:
- The
useFormInput
hook is used to handle the state and change events for both thename
andemail
inputs. - The
handleSubmit
function logs the form values when the form is submitted.
Rules for Custom Hooks
Custom hooks follow the same rules as React hooks:
- Only call hooks at the top level: Do not call hooks conditionally or inside loops.
- Only call hooks from React functions: Custom hooks can only be called from React functional components or other custom hooks.
-
Start with
use
: Custom hooks must start with theuse
prefix to differentiate them from regular JavaScript functions.
Using Custom Hooks for Side Effects
Custom hooks can also be used to handle side effects, like fetching data.
import { useState, useEffect } from 'react';
// Custom Hook to fetch data from an API
const useFetchData = (url) => {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const result = await response.json();
setData(result);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
};
fetchData();
}, [url]);
return { data, isLoading, error };
};
export default useFetchData;
Explanation:
-
useFetchData
is a custom hook that fetches data from an API. - It manages the
data
,isLoading
, anderror
states. - The hook is reusable in any component that needs to fetch data from an API.
Using the Fetch Data Hook in a Component
Here’s how you can use the useFetchData
hook in a component:
import React from 'react';
import useFetchData from './useFetchData';
const DataComponent = () => {
const { data, isLoading, error } = useFetchData('https://api.example.com/data');
if (isLoading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
return (
<div>
<h2>Data:</h2>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default DataComponent;
Explanation:
- The
DataComponent
uses theuseFetchData
custom hook to fetch data from the API. - The component handles loading, error, and displaying the fetched data based on the state returned from the custom hook.
Summary of Custom Hooks
- Custom hooks allow you to encapsulate and reuse logic in your React application.
- They help keep your components clean by abstracting away complex logic.
- Custom hooks can use built-in hooks like
useState
,useEffect
, and others, and they follow the same rules as React hooks. - Common use cases for custom hooks include managing form inputs, fetching data, handling side effects, and more.
Top comments (0)