useEffect on mount code example

Example 1: use effect like component did mount

useEffect(() => {
	console.log('I am the new componentDidMount')
}, [])
// Don't forget the empty array at the end

Example 2: useeffect with cleanup

useEffect(() => {
	//your code goes here
    return () => {
      //your cleanup code codes here
    };
  },[]);

Example 3: useeffect react

useEffect(() => {
	//  code goes here
    return () => {
      // cleanup code codes here
    };
  },[]);

Example 4: useEffect

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    

You clicked {count} times

); }

Example 5: componentwillunmount hooks

useEffect(() => {
  window.addEventListener('mousemove', () => {});

  // returned function will be called on component unmount 
  return () => {
    window.removeEventListener('mousemove', () => {})
  }
}, [])

Example 6: useeffect on update

const isInitialMount = useRef(true);

useEffect(() => {
  if (isInitialMount.current) {
     isInitialMount.current = false;
  } else {
      // Your useEffect code here to be run on update
  }
});

Tags: