React question detail
What are the best practices for using React Hooks?
Following best practices ensures your hooks are predictable, maintainable, and bug-free.
1. Follow the Rules of Hooks
- Only call hooks at the top level (not inside loops, conditions, or nested functions)
- Only call hooks from React functions (components or custom hooks)
2. Use the ESLint Plugin
npm install eslint-plugin-react-hooks --save-dev
{
"plugins": ["react-hooks"],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
}
}
3. Keep Hooks Focused and Simple
// ❌ Bad: One hook doing too much
function useEverything() {
const [user, setUser] = useState(null);
const [posts, setPosts] = useState([]);
const [theme, setTheme] = useState('light');
// ... lots of unrelated logic
}
// ✅ Good: Separate concerns
function useUser() { /* user logic */ }
function usePosts() { /* posts logic */ }
function useTheme() { /* theme logic */ }
4. Use Descriptive Names for Custom Hooks
// ❌ Bad
function useData() { }
// ✅ Good
function useUserAuthentication() { }
function useFetchProducts() { }
function useFormValidation() { }
5. Properly Manage Dependencies
// ❌ Bad: Missing dependency
useEffect(() => {
fetchUser(userId);
}, []); // userId is missing
// ✅ Good: All dependencies listed
useEffect(() => {
fetchUser(userId);
}, [userId]);
6. Avoid Inline Object/Function Dependencies
// ❌ Bad: New object on every render
useEffect(() => {
doSomething(options);
}, [{ page: 1, limit: 10 }]); // Always different reference
// ✅ Good: Memoize or extract
const options = useMemo(() => ({ page: 1, limit: 10 }), []);
useEffect(() => {
doSomething(options);
}, [options]);
7. Clean Up Side Effects
Always return a cleanup function when subscribing to events, timers, or external data sources.