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; 
1

1 Answer 1

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

2 Comments

Thanks for the help. Other than if-condition do you have any other solution? If yes, then please share.
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.