Have you ever wondered why this hook is called useEffect ?
Simply because it manages the side-effects of a component, But what are side-effects?
Side-effects
side-effects can be any thing that does not target the output value of the function for examples:
- Asynchronous api calls to fetch data
- Setting a subscribtion to an observable
- Manually updating the dom
- Updating global variables from inside a function Code example :
import {react} from 'react'
function Greet({name}){
const message = "Hello, ${name}";
document.title = message; // this is a side-effect
return <div>{message}</div>
}
Arguments
the useEffect hook accepts two arguments
useEffect(callback function , [dependencies])
- The callback function is to execute the side-effects you want to happen after the render.
- The array of dependencies is to tell the useEffect hook when to execute the callback function that performs the side-effects.
The dependencies array
the dependencies array argument can be in three forms:
- Not provided => means that the callback function will be executed after each render and that may cause an infinite loop
import {react} from 'react'
function Greet({name}){
const message = "Hello, ${name}";
useEffect(()=>{
document.title = message;
})
return <div>{message}</div>
}
- Provided as an empty array => means that the callback function will be executed after the initial render only [Mounting]
import {react} from 'react'
function Greet({name}){
const message = "Hello, ${name}";
useEffect(()=>{
document.title = message;
},[])
return <div>{message}</div>
}
- Has dependencies => usually the dependencies are props and state and the callback function will be called after the initial render and after the change of any dependency
import {react} from 'react'
function Greet({name}){
const message = "Hello, ${name}";
useEffect(()=>{
document.title = message;
},[name])
return <div>{message}</div>
}
Clean up
The useEffect hook always expects to return nothing or to return a function this function is used for clean up. Some side-effects need a clean up like to clean up a timer or to close up a socket connection.
import {react} from 'react'
function Greet({name}){
const message = "Hello, ${name}";
const timer = useEffect(()=>{
setInterval(()=>{
document.title = message;
},2000)
return function cleanUp(){
clearInterval(timer);
}
},[name])
return <div>{message}</div>
}
Final Note:
The callback function cannot be async because async functions return a promise and the useEffect hook always expects the callback function wheather to return nothing or to return a clean up function
More resources:
Dimitri Pavlutin article => Link
Ben Awad youtube video => Link
If you arrived to this point I hope you enjoied the article and learned somthing new ^^ .
Top comments (3)
I enjoyed your article thank you for your effort.
Good write up. Adding markdown syntax highlighting will improve it though.
Yes I will try to use it next time thanks for your helpfull feedback :)