React clean-up function, what is wrong? - reactjs

Regarding the official documentation clean-up function of react with useEffect help should be called only once and before component will be destroyed.
So regarding this information I made a component and put some code for example let it be the next one
useEffect(() => {
console.log('didmount')
return () => {
console.log('will unmount2')
}
})
I expect to see a several didmount consoles, depending on how many times I'm going to changes props of it and only one "will mount2" before I change my route, so component will be destroyed,
but actual result is next
What I've just missed ?

You didn't understand or fully read the docs.
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.
Changing the props causes the component to rerender. Which in turn causes the clean-up function to be executed.
For your example this means that you should see serveral didmount and will unmount2 in the console depending on how many times the component did rerender.

hello Artem in your function you are missing the second param wich is the dependency array, without this array will cause an infinite loop ill suggest to try this
// this will run exactly when the unmount component, not when the effects finishing running
useEffect(() => {
return () => {
console.log('unmount')
}
}, [])

Related

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

question on code snippet useEffect with fetching state

I am reading this code snipper https://reactjs.org/docs/hooks-faq.html#how-can-i-do-data-fetching-with-hooks linked from react documentation page https://reactjs.org/docs/hooks-faq.html#how-can-i-do-data-fetching-with-hooks
I don't understand this piece of code with the returned function that modifies the ignore variable
useEffect(() => {
let ignore = false;
async function fetchData() {
const result = await axios('https://hn.algolia.com/api/v1/search?query=' + query);
if (!ignore) setData(result.data);
}
fetchData();
return () => { ignore = true; }
}, [query]);
once the function that is passed to useEffect is called a second time, doesn't ignore reset back to false leaving the ignore = true completely useless. The code above does not compute for me. Thanks for explaining.
The ignored variable is in function scope, current effect's ignored will be a different instance with the one in the next effect.
If an effect returns a cleanup function, React invokes it when the component unmounts or before the effect gets re-run due to a dependency change (if query were to change in this case).
The axios fetch call is asynchronous, so it's possible that the component will unmount or a dependency (e.g. query) will have changed before the data request completes.
If that happens, the returned function will have set ignore to true and the fetchData function won't try to call setData on the unmounted component. (Attempting to update state on an unmounted component causes an error.)
From the docs:
When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.
Due to the way javascript closures work, the cleanup function can access the ignore variable in the enclosing scope.
When the effect runs again, a new ignore variable gets declared with a new cleanup function that references the new variable.
Your understanding of the functional call and variable assignment is correct, but you forgot the power of the async call :)
useEffect is called whenever it is needed (e.g. componentDidMount, componentDidUpdate by query keyword), so we roughly have
ignore = false
function fetchData is now defined
function fetchData is called
keep the reset of useEffect in your mind for a sec.
let's say something happens which causes a re-render e.g. prop-change (but other than query) or even call that setData with newly fetched data.
your useEffect will affect nothing, cause query shallow-comparison can not find a change with the previous one. So the purpose of the ignore is not involved in this case, cause it is not going to change at all.
Also if the query change in any way the function execution would roughly (ignoring event loop, macro task everything for the moment) be something like:
// ignore is false and for some reason query changes...
(() => { ignore = true })() // ignore = true
// continue running useEffect again.
// lets think nothing else will happend in gap
ignore = false // ignore = false
The only possible scenario I can think about is when your component is going to be unmounted when your useEffect fallback is being called. So here is when that async keyword wants its dignity back 🙌️.
Remember: The async function is not return anything by your command.
Imagine the data arrive when your component is fully removed from the DOM, here is the role which that ignore=true plays in this useEffect.
Preventing setData on unmounted component

Why useState cause re-render so many times

I am investigating why the useState cause render so many time like the following app, or here
import React from "react";
export default function App() {
const [name, setName] = React.useState("unknown");
console.log("render...", name);
React.useEffect(() => {
const doIt = async () => {
await new Promise(res => setTimeout(res, 1000));
setName("Ron");
};
doIt();
}, []);
return <div className="App">{name}</div>;
}
I think it should render 2 times, 1 is for initial, plus the useEffect. But why it actually render 4 times as below?
render... unknown
render... unknown
render... Ron
render... Ron
The console statement is in the function body, React will execute the function body on each render.
On component mount, As the init state is empty, the console will print an empty string.
As you are updating the state on component Mount, React will execute the function body again and then log the state with the updated value.
As you are using the React.StrictMode it can render the component more than once. That is the reason you see the console logs multiple times.
The commit phase is usually very fast, but rendering can be slow. For this reason, the upcoming concurrent mode (which is not enabled by default yet) breaks the rendering work into pieces, pausing and resuming the work to avoid blocking the browser. This means that React may invoke render phase lifecycles more than once before committing, or it may invoke them without committing at all (because of an error or a higher priority interruption).
Render phase lifecycles include the following class component methods:
constructor
componentWillMount (or UNSAFE_componentWillMount)
componentWillReceiveProps (or UNSAFE_componentWillReceiveProps)
componentWillUpdate (or UNSAFE_componentWillUpdate)
getDerivedStateFromProps
shouldComponentUpdate render
setState updater functions (the first argument)
Because the above methods might be called more than once, it’s important that they do not contain side-effects. Ignoring this rule can lead to a variety of problems, including memory leaks and invalid application state. Unfortunately, it can be difficult to detect these problems as they can often be non-deterministic.
You can read more about React.StrictMode here
This is because you are doing setState in useEffect without any dependency. So whenever you component is rendering, the use effect is working as componentDidMount and then inside of this, there is a setState which cause another rerender and again it calls componentDidmount. Its kinda looping the whole process.

Resources