Learn the concept
Hooks
Custom hooks are JavaScript functions starting with 'use' that encapsulate reusable stateful logic. They can use other hooks and share logic between components without duplicating code or adding components to the tree.
What Custom Hooks Do:
Rules for Custom Hooks:
Common Custom Hook Patterns:
function useLocalStorage(key, initialValue) {
// Get stored value or use initial
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
// Update localStorage when value changes
const setValue = (value) => {
try {
// Allow value to be a function (like useState)
const valueToStore = value instanceof Function
? value(storedValue)
: value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
}
// Usage
function App() {
const [theme, setTheme] = useLocalStorage('theme', 'light');
const [user, setUser] = useLocalStorage('user', null);
return (
<button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
Theme: {theme}
</button>
);
}Custom hooks encapsulating API calls, caching, error handling, and retry logic
Reusable form hooks that handle validation rules, error messages, and submission state
Custom hooks that track page views, user interactions, and feature usage
Build a comprehensive form hook with validation, dirty tracking, and submission handling
Create a hook that manages WebSocket connections with reconnection, heartbeat, and message queuing