Introduction
Custom hooks help you reuse code easily in React. They keep your components clean and simple by sharing logic.
Custom hooks help you reuse code easily in React. They keep your components clean and simple by sharing logic.
function useCustomHook() { // use React hooks here return someValue; }
import { useState } from 'react'; function useCounter() { const [count, setCount] = useState(0); const increment = () => setCount(count + 1); return { count, increment }; }
import { useState, useEffect } from 'react'; function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { const handleResize = () => setWidth(window.innerWidth); window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return width; }
This example shows a custom hook useToggle that manages a boolean state. The component uses it to toggle text between ON and OFF with a button.
import React, { useState } from 'react'; function useToggle(initialValue = false) { const [value, setValue] = useState(initialValue); const toggle = () => setValue(!value); return [value, toggle]; } export default function ToggleComponent() { const [isOn, toggleIsOn] = useToggle(); return ( <> <p>The switch is {isOn ? 'ON' : 'OFF'}</p> <button onClick={toggleIsOn} aria-pressed={isOn} aria-label="Toggle switch"> Toggle </button> </> ); }
Always name custom hooks starting with 'use' so React knows they follow hook rules.
Custom hooks help keep your components smaller and easier to read.
You can combine multiple hooks inside a custom hook to share complex logic.
Custom hooks let you reuse stateful logic across components.
They keep your code clean and organized.
Always start their names with 'use' to follow React conventions.
function useCounter() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
const timer = setInterval(() => setCount(c => c + 1), 1000);
return () => clearInterval(timer);
}, []);
return count;
}
function Counter() {
const count = useCounter();
return {count};
}function useData() {
const [data, setData] = React.useState(null);
fetch('https://api.example.com/data')
.then(res => res.json())
.then(json => setData(json));
return data;
}
function App() {
const data = useData();
return <div>{JSON.stringify(data)}</div>;
}Pass the test and this pattern moves unknown