- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Writing Custom Hooks
Custom Hooks and Patterns
Writing Custom Hooks
A custom hook is not a React feature. It is a function whose name starts with
useand which calls other hooks - that convention is the entire mechanism.
Extracting logic, not markup
Components share markup. Hooks share behaviour. When two components need the same stateful logic but look nothing alike, a hook is what you want.
From duplicated logic to one hook
jsx
// The hook: all the logic, none of the markup.
function useToggle(initial = false) {
const [on, setOn] = React.useState(initial)
const toggle = () => setOn((v) => !v)
return [on, toggle]
}
function Panel() {
const [open, toggleOpen] = useToggle(true)
return (
<div>
<button onClick={toggleOpen}>{open ? "Collapse" : "Expand"}</button>
{open && <p>Panel body</p>}
</div>
)
}
function Switch() {
const [on, toggleOn] = useToggle()
return (
<p>
<label>
<input type="checkbox" checked={on} onChange={toggleOn} /> {on ? "On" : "Off"}
</label>
</p>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<div><Panel /><Switch /></div>)