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; 
2
  • 1
    stackoverflow.com/questions/53253940/… Commented May 14, 2022 at 8:49
  • You can skip a render in useEffect only by using an if statement. Why don't you want to use it? Commented May 14, 2022 at 9:01

1 Answer 1

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; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.