Umut Çakmak

Umut Çakmak

What is the ReactJs useEffect?

What is the ReactJs useEffect?

Umut Cakmak
·Oct 13, 2021·

Subscribe to my newsletter and never miss my upcoming articles

With the useEffect hook, the properties of componentDidUpdate, componentDidMount, componentWillUnmount methods can be used.

componentDidMount() : Runs when the component is first loaded, never again runs.

componentDidUpdate() : Runs when the component is refreshed.

componentWillUnmount() : method is executed when a component is removed from the DOM or completely destroyed

useEffect(() => {
      console.log("useEffect")
  });

useEffect will run when the component is first loaded and every time the component is loaded.

If you want it to work once . You must add an empty dependency array.

useEffect(() => {
      console.log("useEffect")
  }, []);

You can add one or more values to the dependency array. When we add the counter statet to the dependency array, the code in useEffect will run every time the button is clicked.

useEffect(() => {
      console.log("useEffect")
  }, [counter,counter2]);

If we want to use the useEffect hook like componentWillUnmount, we can use it by returning it in useEffect.

useEffect(() => {
     const timer = setInterval(() => {
       setTimer(timer => timer + 1);
   }, 1000);

     return () clearInterval(timer);

  }, []);

Thanks for reading.