Understanding useEffect

  • React
  • Examples
  • Understanding useEffect

React example • 1 min read

  • useEffect
import React, { useState, useEffect } from "react";

function Counter() {
  const [counter, setCounter] = useState(0);

  useEffect(() => {
    console.log("Component mounted!");

    return () => {
      console.log("Component unmounted!");
    };
  }, []);

  useEffect(() => {
    console.log(`Counter has changed to: ${counter}`);
  }, [counter]);

  return (
    <div>
      <p>Counter: {counter}</p>
      <button onClick={() => setCounter((prevCounter) => prevCounter + 1)}>
        Increment
      </button>
    </div>
  );
}

export default Counter;

Example: https://codesandbox.io/s/clglvv