Careeroza
Creating a Custom Hook
What is a Custom Hook?
A custom hook is a normal function whose name starts with use and that calls other hooks. It shares logic, not state: each component that calls it gets its own state.
useToggle and useLocalStorage
Example
Refresh the preview: the saved name is still there because useLocalStorage stores it.
import { useState, useEffect } from 'react';
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = () => setOn((v) => !v);
return [on, toggle];
}
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
try { return JSON.parse(localStorage.getItem(key)) ?? initial; } catch { return initial; }
});
useEffect(() => {
try { localStorage.setItem(key, JSON.stringify(value)); } catch {}
}, [key, value]);
return [value, setValue];
}
export default function App() {
const [open, toggleOpen] = useToggle();
const [name, setName] = useLocalStorage('demo-name', '');
return (
<div>
<button onClick={toggleOpen}>{open ? 'Hide' : 'Show'} details</button>
{open && <p>Here are the details.</p>}
<p><input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name (saved)" /></p>
</div>
);
}Result