Mr. Robot
Mr. Robot

Reputation: 1824

How can I update state in a component from a hook where that hook is used without causing infinite re-renders?

I have the following component:

const CallScreen = () => {
  const [callEnded, setCallEnded] = useState(false);
 
  const updateTimerColor = () => {
    setCallEnded(true);
  };

  const clock = useTimer(
    callStartTime,
    callLength,
    callTimeOut,
    timerReady,
    connectionState,
    updateTimerColor,
  );

Then in useTimer I want to call updateTimerColor when certain conditions are met. The problem is is that when the state updates, the hook is called again and because the conditions under which updateTimerColor is called are the same, the component infinitely re-renders.

How can I update state in CallScreen from the hook without creating an infinite loop?

TIA.

Upvotes: 0

Views: 17

Answers (1)

Çağatay Sel
Çağatay Sel

Reputation: 810

You should also include how you call updateTimerColor but maybe checking if callEnded changed value since last call before calling setCallEnded might prevent the infinite loop.

 const updateTimerColor = () => {
   //No need to set it again if the value did not change
   if(!callEnded) {
     setCallEnded(true);
   }
 };

Upvotes: 1

Related Questions