React Hooks
1) useEffectHooks(,[]);
In order to run some code after the component mounts or after the component updates, then we use componentDidMount and componentDidUpdate lifecycle methods in class based components respectively.
As we cannot use these lifecycle methods in functional components, we can use useEffect() hook instead.
useEffect() method gets executed in both cases i.e. after first render and every time the component gets updated.
How use Effect works-
1) useEffect(); ---> with no second argument . In this case the effect runs on the every render cycle.
- Here this effect will work as componentDidMount() and ComponentDidUpdate().
useEffect(() => {
//Runs on every render
});
2) useEffect(,[])---> Empty array as Second argument In this case the hook will run only for the first render cycle.
- Here it will work as componentDidUpdate();
useEffect(() => {
//Runs only on the first render
}, []);
3) useEffect(,[stateVar1])---> When an non empty array is passed as second argument.
Here it work as componentDidMount() and componentDidUpdate();
useEffect(() => { //Runs on the first render //And any time any dependency value changes }, [prop, state]);
In this case the Hook will run i) on first render ii) when particular dependency changes.
Effect Cleanup
- Some effects require cleanup to reduce memory leaks.
- Timeouts, subscriptions, event listeners, and other effects that are no longer needed should be disposed.
- We do this by including a return function at the end of the useEffect Hook.
import { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
return () => clearTimeout(timer)
}, []);
return <h1>I've rendered {count} times!</h1>;
}
ReactDOM.render(<Timer />, document.getElementById("root"));