React communicate between component

Viewed 50

I have context, where the state of the variable is getting updated every second. And I want invoke functions in other component whenever the variable in the state reaches certain value [second equals 0]

State in the context

const initialState = {
  second: new Date().getSeconds()
};

I'm able to get the value is other components as below

  const [secState, dispatch] = useContext(SecContext);
 `secState.second`
  1. Can someone please guide how to invoke a function when secState.second is zero

  2. I thought of triggering event in the useContext whenever the value reaches zero and listening on other component. not sure how to do it in react any hints or reference please

1 Answers

Inside your components you can have an effect that runs when the context's second value updates, and executes something if it's 0. So in the component:

useEffect(() => {
    if (second === 0) {
        // Do stuff here
    }
}, [second]);
Related