'React hooks - trigger useEffect when a nested property changes in a collection of objects
A page displays a list of objects [{name:, age:}, ...]
A second page allows to update the name of a particular object.
Then using hooks, how should I implement useEffect() so the list on the front page updates only when a name change has been detected?
const [objects, setObjects] = useState([]);
useEffect(()=> {
getAllObjects()
},[getAllObjects, objects]);
Solution 1:[1]
Instead of passing the entire object to the dependency array, make sure that you only pass name. Which you can do by returning the names
const [objects, setObjects] = useState([])
useEffect(()=> {
getAllObjects()
}, [getAllObjects, ...objects.map(item => item.name)])
Solution 2:[2]
One can just do:
useEffect(()=> {
// do something
}, [values.name])
It's a fine solution if the object property always exists however if the property is not present at some point you get a reference error. A workaround in this scenario is to check if prop exists inside the hook
useEffect(()=> {
if (values?.name) {
// do something
}
}, [values])
Solution 3:[3]
Please add JSON.stringify for the nested object.
useEffect(()=> {
getAllObjects()
},[getAllObjects, JSON.stringify(objects)]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shubham Khatri |
| Solution 2 | Alexander |
| Solution 3 | Rayees Pk |
