1

I have a number variable in my react project that changes every couple of minutes.

I would like to make a popup on the screen that displays whether or not the number increased or decreased.

I'm having trouble figuring out a way to make a function that is always running and can detect when that number variable changes.

3
  • 1
    Please share your code showing what you have tried already Commented Nov 6, 2021 at 6:10
  • What changes the variable? There are many ways to do it. Pass it as a prop. Put it in context. Put it in state. Have it emit an event. Commented Nov 6, 2021 at 6:14
  • I figured it out using useEffect(). I simply set my changing variable to a const and passed it through in [] of useEffect(). Commented Nov 7, 2021 at 23:11

1 Answer 1

7

If you are using functional components you can use the useEffect hook, like this

useEffect(()=>{
    //call your increment function here
},[someVariable]) //and in the array tag the state you want to watch for

the useEffect will cause a re-render when the state of 'someVariable' in the above example changes

you can see more about the hook in the react docs https://reactjs.org/docs/hooks-effect.html,

Sign up to request clarification or add additional context in comments.

3 Comments

You may want to call the alert instead of the increment function inside the useEffect, (that could actually create and infinite loop).
Yes It could, thank you for correcting me @programandoconro , as long as the increment function updates the state for the target variable from any where it should work fine
@KirubelEneyew so I would have to make someVariable into a useState? the variable that's changing is a price feed that is read from a smart contract on ethereum. essentially the variable (price) changes every 3 minutes. What's the best way to use useState here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.