Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]); 
like image 351
Yannick Avatar asked May 06 '19 18:05

Yannick


People also ask

Does useEffect work with 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.

Is useEffect called when props change?

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).

How does useEffect get triggered?

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.

Can you use useEffect conditionally?

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.


2 Answers

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)]) 
like image 85
Shubham Khatri Avatar answered Oct 05 '22 19:10

Shubham Khatri


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]) 
like image 44
Alexander Avatar answered Oct 05 '22 19:10

Alexander