0

I want to prevent calling my useEffect on the first mount. how can I do this? I want the best practice. I don't want to use if condition

import { useState, useEffect } from "react";

const Counter = () => {
  const [count, setCount] = useState(5);

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

  return (
    <div>
      <h1> Counter </h1>
      <div> {count} </div>
      <button onClick={() => setCount(count + 1)}> click to increase </button>
    </div>
  );
};

export default Counter;

hossein fti
  • 900
  • 1
  • 6
  • 12
  • 1
    https://stackoverflow.com/questions/53253940/make-react-useeffect-hook-not-run-on-initial-render – Blind2k May 14 '22 at 08:49
  • You can skip a render in useEffect only by using an if statement. Why don't you want to use it? – Amit May 14 '22 at 09:01

1 Answers1

0

I found it. It should be handled by useLayoutEffect and useRef

import { useState, useEffect, useLayoutEffect, useRef } from "react";

const Counter = () => {
  const [count, setCount] = useState(5);

  const firstUpdate = useRef(true);

  useLayoutEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }
    console.log(count);
  });

  return (
    <div>
      <h1> Counter </h1>
      <div> {count} </div>
      <button onClick={() => setCount(count + 1)}> click to increase </button>
    </div>
  );
};

export default Counter;

hossein fti
  • 900
  • 1
  • 6
  • 12