Do Not Overuse Useeffect
Topic | Source |
---|---|
๐งฉ React | Top 6 React Hook Mistakes Beginners Make - YouTube |
You don't always need a
useEffect
to update values after an update.
useEffect
triggers a complete re-render of the component. Pay attention when you really needs the re-render, and when a simple const
could also do the trick.
Take a look at this example:
const [firstname, setFirstname] = useState("");
const [lastname, setLastname] = useState("");
const fullname, setFullname = useState("");
useEffect (() => {
setFullname(`${firstname} ${lastname}`)
}, [firstname, lastname]);
This updates the full name every time, either the first, or the last name changes. So the update of the first name triggers a re-render, and then useEffect
triggers another one. Since the first useState
already causes a re-render, we can simply update a const
instead
const [firstname, setFirstname] = useState("");
const [lastname, setLastname] = useState("");
const fullname = `${firstname} ${lastname}`