Custom hooks in React are a powerful way to encapsulate and share logic across components. They allow developers to extract component logic into reusable functions, making code cleaner and more maintainable. By following best practices and understanding common pitfalls, you can effectively utilize custom hooks in your projects.
To create a custom hook, you simply define a function that starts with the word "use". This convention is important as it allows React to identify the function as a hook. For example, let's create a custom hook that manages a counter.
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return { count, increment, decrement };
}
Once the custom hook is created, it can be used in any functional component. Here’s how you can implement the `useCounter` hook in a component:
function CounterComponent() {
const { count, increment, decrement } = useCounter(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
Another common use case for custom hooks is fetching data. Here’s an example of a custom hook that fetches data from an API:
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Network response was not ok');
const result = await response.json();
setData(result);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
This custom hook can be used in any component that needs to fetch data, making it reusable and efficient.