When to use useEffect?
Mohamed Amine Dridi, PSM?, SAFe? 6
Entreprise Architect | Solution Architect | Data Architect | Technical Architect | Senior Software Engineer | Team Lead | Scrum Master | UI&UX Design | DevOps | AWS Cloud Administration | Release Management
Most developers don't fully understand its purpose...
Here are some simple and quick-to-grasp use cases
0?? The purpose of useEffect
"useEffect is a React hook that allows you to synchronize a component with an external system."
Two key words stand out:
1.???? "Synchronize" not "manage lifecycle"
2.???? "External system" -> external to... React!
An External system is ANYTHING outside of what React manages.
Because React already handles the DOM of our code, but sometimes we want to interact with it or other systems directly.
1?? Synchronization with the browser
The first, very simple use case for useEffect is to synchronize the title of our page:
?
JavaScript
?useEffect(() => { ?
document.title = Count: ${count};
}, [count]);
document.title is outside of React's render = useEffect
PS: From version 19, it will be possible to include the title tag: https://lnkd.in/g9EBwufb
领英推荐
2?? Synchronization with events
Another well-known example is when you want to add an event listener.
useEffect is there to synchronize your component with window events, for example.
But as soon as you synchronize, you also want to clean up!
What is the useEffect cleanup function?
useEffect(() => {
//your side effect here
effect()
return () => {
//remove side effect here
cleanup()
}
}, [dependencies])
Cleanup allows you to remove what the effect has created.
Because an effect is a "side effect" and we don't want to keep an infinite number of "side effects" in our application.
That's why you should always clean it up.
3?? Synchronizing with websockets
You're obviously not always forced to synchronize with the DOM, but you can also do it with WebSockets, for example.
It's always an external system that you're synchronizing with your component.
4?? Misuses of useEffect
To know what NOT to do with useEffect, the answer is simple:
●?????? Do something other than "synchronize"
For example, a useEffect that focuses on an element on the page is not the best method, you can use the ref prop.