Custom Hooks: Best Practices and Patterns
1 min read
Share
Building Reusable Logic with Custom Hooks
Custom hooks are the most elegant way to share stateful logic between React components. Let's explore patterns that make your hooks maintainable and reusable.
The Rules of Hooks
- Only call hooks at the top level
- Only call hooks from React functions
- Name custom hooks starting with "use"
A Practical Example: useAsync
function useAsync(asyncFn, deps = []) {
const [state, setState] = useState({
loading: true,
error: null,
data: null
});
useEffect(() => {
asyncFn()
.then(data => setState({ loading: false, error: null, data }))
.catch(error => setState({ loading: false, error, data: null }));
}, deps);
return state;
}
This hook encapsulates the common pattern of loading, error, and data states for async operations.
