0

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;
  • 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) – kishore Rajendran Sep 01 '21 at 09:59

1 Answers1

0

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;
Prateek Thapa
  • 4,829
  • 1
  • 9
  • 23
  • Thanks for the help. Other than `if-condition` do you have any other solution? If yes, then please share. –  Sep 01 '21 at 10:17
  • What's wrong with `if-condition` if I may ask? You could use a `ref` and check it to bypass first render, but that would be unnecessary in your use-case. A simple `if-condition` would do. – Prateek Thapa Sep 02 '21 at 08:14