1

I was doing my work and I wondered why useEffect detects a change when a useState() variable starts with a default value, and how to prevent that

  const [startDate, setStartDate] = useState(0);

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

First rendered of the useEffect with be the value of 0, how to prevent that the useEffect detects the default value?

Christian
  • 481
  • 1
  • 7
  • 24
  • [This](https://stackoverflow.com/questions/53253940/make-react-useeffect-hook-not-run-on-initial-render) might help – Danny Buonocore Apr 18 '21 at 17:17
  • 1
    `useEffect` runs at least once on when the component is mounted ... it's not reacting to `useState` having a initial value. – Deiknymi Apr 18 '21 at 17:18
  • Does this answer your question? [Make React useEffect hook not run on initial render](https://stackoverflow.com/questions/53253940/make-react-useeffect-hook-not-run-on-initial-render) – barshopen Apr 18 '21 at 17:18
  • you can always add an `if` inside the `useEffect` to check whether it is initial value or not – crollywood Apr 18 '21 at 17:19

2 Answers2

1

useEffect runs by default on component mount

To prevent that you need to use a ref that will tell you if it is the first effect or not

const isMountedRef = useRef(false)

useEffect(()=>{
    if(isMountedRef.current)
        console.log(startDate)
    else
        isMountedRef.current=true
},[startDate])

you can extract the logic in a custom hook

const useUpdateEffect=(effect, deps)=>{
    const isMountedRef = useRef(false)

    useEffect(()=>{
        if(isMountedRef.current)
            effect()
        else
            isMountedRef.current=true
    },deps)
}

And use it as follows

useUpdateEffect(()=>{
    console.log(startDate)
},[startDate])
L.Blondy
  • 277
  • 1
  • 6
0
const [startDate, setStartDate] = useState(0);

  useEffect(() => {
    if (startDate != 0) {
      console.log(startDate)
    }
  })

this will detect changes expect for when the value is 0 (the default value)

Nitai
  • 73
  • 6