Dependencies in React useEffect cleanup function are not updated - reactjs

I am facing a strange issue when trying to call a cleanup function on component unmount with useEffect.
In my useEffect return I call a useCallback function where the dependencies are added correctly. In there a check the state variable called status but this variable never get updated from the initial state. I cannot pass the variable to the useEffect as I want to trigger it only when the component unmounts for specific reasons.
I recreated a simplified version in the codepen here and I can't get my head around this. Maybe someone knows why this is happening?
Thank you!
(this just started happening recently and it was working previously so I'm even more confused!)

Thank you for your answers.
So, I finally found out what happens.
useEffect creates a closure and the function is in that closure, which means that the status, being a string, remains as for the first render (when the closure gets created) and it never gets updated.
A way of giving this is using useRef, as mentioned by #ilkerkaran, but that's because it creates an object, which means that the ref.current property has a link to the original one and it's always in sync.
Another way would be to do useMemo and return an object with the status property, which is practically useRef under the hood.
So practically, if the state were an object and we passed state as a dependency, the stayus property would work as expected for the same reason. I hope this helps also someone else and saves some time

Actually that's not what happens on your code. The callback function is updated according to dependency array. You can see that by calling remove() just above useEffect. That way, the func will be executed on every render.
What happens in your example;
it renders, (by pressing the toggle button for the first time)
then you trigger second render by calling setStatus("mounted") in useEffect (by pressing the toggle button for the second time)
then it renders for te last time for unmount with the default state values
Last part also bugs me actually. You can observe this behaviour by putting a simple console.log just above your useEffect definition.
You also can work around this by using useRef instead of useState

The reason for this is your useEffect .
React.useEffect(() => {
setStatus("mounted")
return () => remove()
}, [])
You have an useEffect with the dependency set to []. This means that your useEffect will run only once . So this is how the flow goes your component is executed from the top to bottom so you create a remove function which at this point of time has your initial state as not mounted . Now your dom get painted. You useEffect gets called you set the state now you get a brand new remove function . Now you unmount your component the clean up will use the remove function from the first render.
In order for your state to reflect in the remove you need to add status as the dependency in the useEffect .
React.useEffect(() => {
setStatus("mounted")
return () => remove()
}, [status])

Related

React state change is one step behind

A common problem in React, especially among beginners (like me). This is due to the fact that setState is an asynchronous function and React does not change values one by one, but accumulates some pool if it is not otherwise instructed. (please correct me if the wording is wrong)
So here's the question. One simple solution is to put the desired state into the useEffect dependency array.
For example, I have such a component:
const [first, setFirst] = useState()
const [second, setSecond] = useState()
useEffect(() => {
Something logic by first and second...
}, [first])
Here, the useEffect is executed every time the first state changes. At the same time, at the moment of its operation, the second state is not relevant, next time it will become as it should be now, and so on. Always one step behind.
But if I add a second state to the useEffect dependency array, then everything works as it should.
useEffect(() => {
Something logic by first and second...
}, [first, second])
At the same time, it is not necessary that the useEffect work on changing the second state, I added it only in order to have an up-to-date version inside the useEffect. Can I use the useEffect dependency array this way?
if you use useEffect with an empty array it will act as componentDidMount and componentWillUnmount so it will only invoke itself on first component creation and when it is about to unmount.
https://reactjs.org/docs/react-component.html#componentdidmount
Here I got the problem You are facing, I am not fully sure, but In my case I was console.log(result) withing the fucntion that was changing state, but it was always one step behind. why was that? because in React it is considered as side effect. So If you console.log(result) in useEffect passing the value in dependency array then, it will console log the same value that instantly changed.
In backgorund the state is updating exactly the same time but useEffect detects it as exactly as it is changed.
You can write any logic in useEffect as well or in the function which you are updating.
So there should not be any problem writing logic in the function which you are callilng on click.

Why does addEventListener accumulate in useEffect hook?

Functionality: entering text into input, creating a list by pressing enter.
https://codesandbox.io/s/awesome-tereshkova-96pf3?file=/src/App.js
I have two addEventListeners. One is outside of any hooks, the other in useEffect.
What is the logic behind the EventListener outside the hooks? Why does it behave so?
Why is the number of clicks doubled when I click on a list item?
What feature does addEventListener have that causes it to be accumulated in the useEffect hook and need to be cleaned up? Why does console.log (), for example, not accumulating?
so your first of all, think of your React components as functions that are called over and over again on each render.
So in your case your first eventListener registered outside of useEffect
document.addEventListener("click", () => console.log("foo"));
this is called every time your component is rendered => in other words, every time your component rerenders new event listener is registered. In your case this happens in this order
User types 1 letter to input box
setTodoTitle is called with new value => this causes react to update your components
new event listener is registered because of rerender
Your second case is a little bit different, cuz you register your event listener in useEffect. Function passed (first param) to useEffect is called only when some variable from dependency array (second param) changes. So in your case useEffect is called only when todos change => after you add new todo on Enter click. You correctly use cleanup function (return {...}) in useEffect. React performs the cleanup when the component unmounts. ... This is why React also cleans up effects from the previous render before running the effects next time [react docs]
component mounts for first time
useEffect is called, because todos didn't exist before and now its set to []
you add new todo
useEffect triggers again, because todos changed

React Functional Component Lifecycle Flow with useEffect, both [] and [var]

My functional component is structured as follows:
// Initialization
useEffect(() => {
fetchDetailedUserInfo();
}, []);
// Update on initialization of detailedUserInfo
useEffect(() => {
if (detailedUserInfo) {
//...
setInitialFormValues(..);
}
}, [detailedUserInfo]);
// Update on initialization of initialFormValues
useEffect(() => {
//...
}, [initialFormValues]);
// Return JSX
return ( .. );
What determines when the render (return) runs in between all these useEffects, and how are the useEffects ordered among themselves? What is the exact flow?
According to docs:
By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.
The clean-up function runs before the component is removed from the UI to prevent memory leaks. Additionally, if a component renders multiple times (as they typically do), the previous effect is cleaned up before executing the next effect. In our example, this means a new subscription is created on every update. To avoid firing an effect on every update, refer to the next section.
A lot of people tend to miss the above statement on the documentation.
There are two behaviours to be noticed.
When there is an empty dependency array []
In this case the cleanup effect will only get called when the component is going to unmount
When there is some dependency in the dep array
In this case, the cleanup effect is called everytime the useEffect is triggered due to the update phase, it will be called first, then the callback function will be called, so as to ensure that any cleanup is done before the next callback is called.
The main reason for this confusion is that when someone comes from class components this is not the case, and they tend to follow the lifecycle diagram provided.
The hooks LC diagram is not really official, and has a small flaw
https://github.com/Wavez/react-hooks-lifecycle/issues/5
I had raised an issue on the github repo as well with the correction.
Its still open though.
Do checkout the docs here
https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect
why dont you do something like this instead?
useEffect(() => {
// you can return the promise inside the fetchDetailedUserInfo function, and ensure that you return the reponse. make sure to add a catch block or handle that in the response.
fetchDetailedUserInfo()
.then(res=>{
setInitialFormValues(...)
})
}, []);
The first useEffect runs when the component is first rendered, so will fire first. The second useEffect will fire whenever detailedUserInfo has changed its value (assuming its not null/false, etc.). The third useEffect will fire whenever initialFormValues has changed its value.

Why useEffect may return a ClearInterval() on a SetInterval effect?

In the following code from reactjs.org:
useEffect(() => {
function tick() {
// Read latest props at any time
console.log(latestProps.current);
}
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []); // This effect never re-runs
as my brain compiles it, the effect created is a "wait one second then do something", but the setInterval being async itself, it returns immediately then useEffect return its closure callback. React being aware of states changes only and not of actions (it doesn't know what was launched in the useEffect, isn't it? How could he know!), I suppose that it'd fire the closure callback directly on return and then prevent the tick() function to be fired even ounce... but it's not the case. How comes ? How React knows what to wait before firing the closure callback returned by useEffect?
While I don't know exactly what happens in the background, for implementation sake you need only to know that the return callback of a useEffect is only called when the effect is re-ran, or more specifically, after "closing" the previous effect-run and before the new effect running. Depending on the effect's dependencies, it can be on every render, or (as in the example you posted) only when the component is unmounted.
It's useful to think that functional components are just functions, so unless the function (the component) is called again (a re-render or other lifecycle change), the effect is "stopped", there's no magical parallel process. I would risk saying that react checks the hooked effects on a component in pre and post render. Depending on dependencies and the effect's details, it knows whether it should call the return callback or not call the effect at all.
See this sandbox I created where I demo these two most extreme cases: effect on every render, and effect only on mount/unmount. Check the sandbox console to understand the behavior. Try to change the parent's effect dependencies to [count] and see the differences.
PS: when I started using hooks, this article helped me a lot https://overreacted.io/a-complete-guide-to-useeffect/

useEffect called when a variable not in the dependancy list is updated (causing an infinite loop)

I'm trying to do an ajax call when a state changes, and then set another state to the result of that ajax call.
const [plc, setPlc] = useState(null);
const [tags, setTags] = useState([]);
...
useEffect(()=>{
if(plc != null) {
myAjaxPromiseFunction(plc).catch((err)=>{
console.log(err);
}).then((tags)=>{
setTags(tags);
});
}
}, [plc]);
For some reason, this results in an infinite loop. However, when I remove the setTags(tags); statement it works as expected. It appears that the setTags function is causing the effect hook to update, but tags is not a part of the dependencies of this effect hook.
FYI, the tags variable is supposed to be a list of objects.
EDIT:
I have one other useEffect in my code.
useEffect(() => { // Update which tags are logged
if(plc != null) {
anotherAjaxFunction(plc, tags).catch(err => {
toaster.show({
message: err,
intent: "danger"
});
}).then(tags => {
setTags(tags);
});
}
}, [plc, updateLoggedFlag]);
However, this useEffect is not dependant on tags, and the issue still occurs if I remove this block of code.
Side note: The updateLoggedFlag is a variable I was planning to use to force the effect to update as needed, but I haven't used it anywhere yet.
Another EDIT: Link to reproduction using code sandbox: https://codesandbox.io/s/cranky-ives-3xyrq?file=/src/App.js
Any ideas? Thanks for the help.
In short: move TagColumn outside of App, as it is here.
The problem is not connected to the effects declaration, it's due to the component declaration.
In your sandbox, the TagColumn was defined inside of App. It means that every time App was rendered (in particular, every time its state is changed), the const TagColumn was assigned a different value. React can't see that it is the same component every time - after all, it's not really the same, since the captured scope is changing.
So, App renders a new TagColumn. React sees that component is created from scratch, renders it, and, in particular, invokes its hooks, including every useEffect. Inside useEffect, you use callback to change the state of App. App rerenders, creates yet another component TagColumn, which is again rendered for the first time in its life, calling every useEffect... and the cycle continues.
In general, you shouldn't capture anything non-constant in the functional component scope. Instead:
if the value is generated by external context (App, in this case) - pass it as props;
if the value is generated by the component itself - use useState, useRef or other hooks, as necessary.
The problem I think with your code is that it does not include tags in the dependency array. Conceptually, this should work fine, as mentioned before by other developers, but React documentation states that, all the state variables and props used inside the callback, should be present inside the dependency array, otherwise it can cause bugs. Have a look at it here. Hooks FAQ

Resources