HOME
Search
Notification
Login
How to prevent useEffect re-render same value?
Author:
| Modified:
2023-11-20 08:02
| Viewed:
299
useEffect first Parameter is the function with your Effect’s logic. The second is dependency, React will compare each dependency with its previous address using the Object.is comparison. There are three way to prevent useEffect re-render same value: 1. use basic data types for dependencies. ``` const Team = ({ team }) => { const [players, setPlayers] = useState([]) useEffect(() => { if (team.active) { getPlayers(team.id).then(setPlayers) } }, [team.id, team.active]) return <Players team={team} players={players} /> } ``` 2. recreate the object within useEffect. ``` const Team = ({ id, name, active }) => { const [players, setPlayers] = useState([]) useEffect(() => { // recreate the `team` object within `useEffect` // from props/state const team = { id, name, active } if (team.active) { getPlayers(team).then(setPlayers) } }, [id, name, active]) const team = { id, name, active } return <Players team={team} players={players} /> } ``` 3. wrap the initialization of object in useMemo() Hook. ``` const Team = ({ id, name, active }) => { // memoize calling `createTeam` because it's // an expensive operation const team = useMemo(() => createTeam({ id, name, active }), [ id, name, active, ]) const [players, setPlayers] = useState([]) useEffect(() => { if (team.active) { getPlayers(team).then(setPlayers) } }, [team]) return <Players team={team} players={players} /> } ``` If all methods above cannot solve the problem, use useRef() to cache object value, and use useDeepCompareEffect Hook from react-use library to compare object value.
javascript
1
reply
In general, I think if a hook is over six dependencies, it's time to consider if we can split a hook to make it smaller or it will be difficult to manage them.
0
2023-11-20
Comment
Submit
Anonymous
Reply
Author
Related Topic
What you need to prepare to be a fullstack?
test
Zustand for State Management in React