useEffect is a hook that manages side-effects in functional components.
A function will always produce the same output when given the same input; these functions are known as Pure functions. This function produces a predictable output.
Side-effects are the actions performed to communicate with the outside world. These actions are unpredictable.
Example of Side-effects
Making an API request.
interacting with DOM.
using localStorage or setTimeout or setInterval functions.
useEffect hook will take two arguments a callback function which will be called after a component render and a dependency array.this array tells react when to call this function.
If no array is passed, useEffect will run at every render.
function MyComponent(){
useEffect(()=>{
console.log("Hello World");
});
}
If an Empty array is passed, useEffect will run only at initial render.
function MyComponent(){
useEffect(()=>{
console.log("Hello World");
},[]);
}
If array with a value inside is passed, useEffect will run whenever that value is changed between renders.
function MyComponent(){
const [value,setValue]=useState(0);
useEffect(()=>{
console.log("Hello World");
},[value]);
}
Comparing Class-based components with Functional-based components.
we should avoid code duplication in componentDidMount and componentDidUpdate. So here we introduce useEffect hook in functional component.
Cleanup function in useEffect
lets say we are using a setInterval function that runs every second and this side-effect is not cleaned up. So whenever our component is unmounted or you moved to the next page this setInterval will still be running in background. This is bad and is known as memory leak.
componentDidMount()
useEffect(()=>{
console.log("component mount");
},[])
componentDidUpdate()
useEffect(()=>{
console.log("component update");
},[values])
componentWillUnmount()
useEffect(()=>{
return ()=>console.log("component removed");
},[])
Top comments (0)