Advanced40 min read
Building Custom Hooks
Create reusable custom hooks to extract component logic and share it across your application.
Topics Covered:
Custom HooksLogic ExtractionHook CompositionBest Practices
Prerequisites:
- Performance Optimization Techniques
Overview
Custom hooks let you extract component logic into reusable functions. They're a powerful way to share stateful logic between components.
What are Custom Hooks?
Custom hooks are JavaScript functions whose names start with 'use' and may call other hooks. They let you reuse stateful logic.
Creating Custom Hooks
Extract logic into a custom hook to share it between components.
Code Example:
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});
const setStoredValue = (newValue) => {
setValue(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
};
return [value, setStoredValue];
}
// Use in component
function Component() {
const [name, setName] = useLocalStorage('name', '');
// ...
}Custom hooks encapsulate logic. They can use other hooks and return any values you want components to use.
Conclusion
Custom hooks are the recommended way to share logic. They keep components clean and logic reusable.