UseEffect summary
side effects, dependencies, cleanup function
When does useEffect run?
useEffect(side effect function(),[dependencies])
The function in useEffect runs right after and for every component render cycle, it also re-runs when dependencies changes.
useEffect(side effect function(), [])
If there is no external dependencies used in the function, we can add an empty array. It will only run once, like component did mount.
What should be put in the dependency array?
Values defined outside of the component. The rule is: if any variable is used inside the hook but is defined outside of it, then it should go in the dependency array
Side effects
Side effects are not predictable because they are actions which are performed with the “outside world.”
We perform a side effect when we need to reach outside of our React components to do something. Performing a side effect, however, will not give us a predictable result.
Think about if we were to request data (like blog posts) from a server that has failed and instead of our post data, gives us a 500 status code response.
Virtually all applications rely on side effects to work in one way or another, aside from the simplest applications.
Common side effects include:
- Making a request to an API for data from a backend server
- To interact with browser APIs (that is, to use
document
orwindow
directly) - Using unpredictable timing functions like
setTimeout
orsetInterval
This is why useEffect exists: to provide a way to handle performing these side effects in what are otherwise pure React components.
Cleanup function
useEffect(
side effect function()
//cleanup function
return ()=>{};,[dependencies])
Cleanup function runs when the component get unmounted. So it runs before the next time the component runs, not after current component runs. Commonly used for clearTimeout
.
useEffect(
const timer = setTimeout(()=>{}, 5000)
return ()=>{
clearTimeout(timer)
}
,[dependencies])
References: