Custom Hooks
45 minCustom hooks are functions that start with 'use' and may call other hooks. They allow you to extract component logic into reusable functions.
Custom hooks can use any of the built-in hooks and can accept parameters and return values.
They're great for sharing stateful logic between components without changing their hierarchy.
Custom hooks follow the same rules as built-in hooks: only call them at the top level, and only call them from React functions.
Naming custom hooks with 'use' prefix is a convention that enables React's linting rules to work correctly.
Custom hooks can return any value - objects, arrays, or single values - making them flexible for different use cases.
Key Concepts
- Custom hooks start with 'use' and can call other hooks.
- They enable sharing stateful logic between components.
- Custom hooks must follow the Rules of Hooks.
- They can accept parameters and return any value.
- Naming convention helps React's linting tools.
Learning Objectives
Master
- Creating custom hooks to extract reusable logic
- Understanding the Rules of Hooks for custom hooks
- Designing hook APIs for different use cases
- Testing custom hooks effectively
Develop
- Code organization and reusability thinking
- Recognizing when to extract logic into hooks
- Designing clean and intuitive hook APIs
Tips
- Start with 'use' prefix for all custom hooks.
- Return objects for multiple values, arrays for ordered pairs.
- Keep hooks focused on a single concern.
- Use TypeScript for better type safety in custom hooks.
Common Pitfalls
- Calling hooks conditionally or in loops (violates Rules of Hooks).
- Creating hooks that are too complex and do multiple things.
- Not following the 'use' naming convention.
- Returning inconsistent data structures from hooks.
Summary
- Custom hooks extract and share reusable stateful logic.
- They must follow the Rules of Hooks.
- Naming with 'use' prefix enables React's linting.
- Custom hooks can return any value structure.
Exercise
Create a custom hook that manages a form input with validation.
import { useState } from 'react';
function useFormInput(initialValue) {
const [value, setValue] = useState(initialValue);
const [error, setError] = useState('');
const handleChange = (e) => {
setValue(e.target.value);
if (e.target.value.length < 3) {
setError('Input must be at least 3 characters');
} else {
setError('');
}
};
return {
value,
onChange: handleChange,
error
};
}
// Usage in component
function MyForm() {
const name = useFormInput('');
return (
<div>
<input {...name} placeholder="Enter name" />
{name.error && <span style={{color: 'red'}}>{name.error}</span>}
</div>
);
}
Exercise Tips
- Add a reset function to clear the input value.
- Consider adding validation rules as parameters.
- Use useCallback for the handleChange function.
- Add TypeScript types for better type safety.