useEffect(() => {
fetchWithRetry(backend_link).then((res) => res.json()).then((res) => {
setData(res);
setLoading(false);
})
},[didPost]);
`Looking at this sample code for useEffect, does this trigger when didPost (useState object) has a state change? Also, when useEffect is triggered in general, does the code instantly stop in its tracks and run the useEffect lines then go back to where it left off?
I have tried to change around the values in the second useEffect parameter but I feel like I am just not understanding how the hook actually functions.
2
Answers
The useEffect hook in ReactJS runs after the first render and after every update. When a dependency is triggered, the useEffect hook will run on the next render, not instantly. This means that the code does not stop in its tracks and run the useEffect lines then go back to where it left off. Instead, the useEffect hook is called after the component has been updated.
In the sample code you provided, the useEffect hook has a dependency array [didPost], which means that it will only run when the value of didPost changes. When didPost changes, the component will re-render and the useEffect hook will run after the render is complete.
Hope this helps!
Although you can use the useEffect(fn, []) construct to reproduce the componentDidMount functionality, it is not the exact equivalent of componentDidMount. Namely, it, unlike componentDidMount, captures properties and state. Therefore, even inside the callback, you will see the original properties and state. If you want to see the latest version of something, you can write it in the ref link. But usually there is an easier way to structure the code, so it is not necessary to do this. Keep in mind that the mental effects model is different from the one applicable to componentDidMount and other methods of the component lifecycle. Therefore, trying to find exact equivalents can do more harm than good. In order to work productively, you need to, so to speak, "think with effects." The basis of their mental model is closer to the implementation of synchronization than to responding to the events of the component lifecycle.