Lesson 29 of 3097%
(Progress persistence is disabled until Phase 9)
React
Beginner
Hook Best Practices
Common pitfalls when working with hooks.
When working with Hooks, keep these tips in mind:
- Don’t lie about dependencies: If you use a state variable or a prop inside
useEffect, you MUST include it in the dependency array. If you don’t, your effect will use stale data. - Don’t overuse
useEffect: If you can calculate a value directly during rendering, don’t use state and an effect to set it. Just calculate it as a normal variable!
// BAD: Unnecessary state and effect
const [firstName, setFirstName] = useState("John");
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(firstName + " Doe");
}, [firstName]);
// GOOD: Calculate during render
const [firstName, setFirstName] = useState("John");
const fullName = firstName + " Doe";
Try It Yourself