useEffect hook in react

useEffect hook can be used to implement below lifecycle methods of component.
  • componentDidMount() - use useEffect and pass empty array as second argument
  • componentDidUpdate() -
    
    const mounted = useRef();
    useEffect(() => {
        if (!mounted.current) {
            // componentDidMount code
            mounted.current = true;
        } else {
            //componentDidUpdate code goes here
        }
    });
    
  • shouldComponentUpdate() - pass dependency array as second argument or call setState conditionally
  • componentWillUnmount() - return a function from useEffect

Adding and removing event listeners


useEffect(() => {
window.addEvenListner('resize','f1')

 return ()=>{
    window.removeEvenListner('resize','f1')
 }
 
})

Fetching data



fetch(`https://jsonplaceholder.typicode.com/posts`)
.then(response => response.json())
.then(json => console.log(json))

Complex problems, Simple Solutions