Search code examples
reactjsrenderuse-effect

how to avoid first default effect in UseEffect


I have implemented the feature that on clicking the button an alert will come that you have clicked but this alert comes in the very first render. I don't want it like that. I want to start alert when the count will be 1 and forward. Can you guys please help me with this?

import React, { useEffect, useState } from 'react';

function Demo() {
  const [num, setNum] = useState(0)

  const change = () => {
    setNum(num + 1)
  }

  useEffect(() => {
    alert(`item clicked ${num} times`)
  }, [num])

  return(
    <div>
      <h1>{num}</h1>
      <button onClick={change}>Count</button>
    </div>
  )
}

export default Demo;

Solution

  • You could simply check for the num using if-statement.

    If num is greater than zero, show alert, otherwise not.

    import React, { useEffect, useState } from 'react';
    
    function Demo() {
      const [num, setNum] = useState(0)
    
      const change = () => {
        setNum(num + 1)
      }
    
      useEffect(() => {
        if (num > 0) alert(`item clicked ${num} times`)
      }, [num])
    
      return(
        <div>
          <h1>{num}</h1>
          <button onClick={change}>Count</button>
        </div>
      )
    }
    
    export default Demo;