skip to Main Content

I am new to react and this is a very simple counter that increments value by 5, I learnt that useEffect is executed after every component re-render/dependency variable change. But I found that useEffect (i.e alert) is appearing before the value in the h1 changes

import { useEffect, useState } from "react";

export default function App() {
const [number, setNumber] = useState(0);

  let prev = 0;

  useEffect(() => {
    if (number !== 0) {
      alert("Number changed to " + number);
    }
  }, [prev, number]);

  console.log(prev);

  return (
    <>
      <h1>{number}</h1>
      <button
        onClick={() => {
          setNumber((n) => {
            prev = n;
            return n + 5;
          });
        }}>
        +5
      </button>
    </>
  );
}

Expected Outcome: alert happens after h1 value increments by 5

Current Result: alert comes first and h1 value increments after closing the alert

2

Answers


  1. useEffect runs basically like componentDidMount,

    so it runs first time after the component mounted and then after every re-render

    Login or Signup to reply.
  2. This is when useEffect runs:

    useEffect(() => {
      /* Runs at every (First time, and anytime the component is rendered) render! */
    })
    
    useEffect(() => {
      /* Runs only when the component is rendered for the first time! */
    }, [])
    
    useEffect(() => {
      /* Runs when the component is rendered for the first time and whenever the someDependency is updated! */
    }, [someDependency])
    

    Therefore, in your case, it runs when the component is rendered for the first time, when the number changes, and when the prev changes. Also, do not change prev the way you are doing it right now, it will cause an infinite loop!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search