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]);
The objects have to be the exact same object in order for useEffect to skip running the effect. So even if the contents are the exact same, if a new object is created for the subsequent render, useEffect will re-run the effect.
Run useEffect When a Prop Changes useEffect can trigger on any of them. In this example, the PropChangeWatch component is receiving 2 props ( a and b ), and its effect will only run when the value of a changes (because we're passing an array containing [a] as the second argument).
By default useEffect will trigger anytime an update happens to the React component. This means if the component receives new props from its parent component or even when you change the state locally, the effect will run again.
The error "React hook 'useEffect' is called conditionally" occurs when we use the useEffect hook conditionally or after a condition that may return a value. To solve the error, move all React hooks above any conditionals that may return a value.
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)])
Check https://dev.to/aileenr/til-you-can-watch-for-nested-properties-changing-in-react-s-useeffect-hook-26nj
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With