Have you ever wondered how you can rerender the component in React to reflect new changes? It’s actually quite simple thanks to the React Hooks and the side effect from the useState that rerenders the component.

Counter

useState returns 2 values, the reference only variable and the function to update the said variable. As a side effect on every update of the state, the component will rerender. The simplest way to demonstrate this behaviour would be with the classic ‘counter’ example. Let’s take a look at the source code.

import { useState } from 'react';

function App() {
  const [counter, setCounter] = useState(0)

  return (
    <div style={{ margin: '50px' }}>
      <h1>{counter}</h1>
      <button onClick={() => setCounter(counter + 1)}>Increment</button>
    </div>
  );
}

export default App;

Our component will update every time we click on the button element. There is a related onClick event handler that uses the setCounter function to update the state variable. The component then rerenders on every click of the button to reflect the new state.

Infinite loop

Make sure that you avoid the infinite loop when using the useState to update your components. It’s very important that you understand the implications of using the function to update the state to avoid the dreadful infinite loop error.

Infinite loop happens when your code calls itself recursively without any break condition. This results in the program run running forever, the only way to stop it would be to crash it or to force quit it.

This can happen when you call the state setter function in the body of your component. Let’s modify the previous example to explain this issue.

import { useState } from 'react';

function App() {
  const [counter, setCounter] = useState(0)
  setCounter(counter + 1)

  return (
    <div style={{ margin: '50px' }}>
      <h1>{counter}</h1>
    </div>
  );
}

export default App;

We have gotten rid of the button and moved the call to setCounter to the body of the function. The component now renders for the first time and it all goes smoothly until it encounters the setCounter call. Set counter updates the state variable but also causes the component to rerender as a side effect. This behaviour will never stop as on every render of the component it encounters the function to update the state over and over again. You can see that the app crashed if you check the console.

errors

👋 Hey, I'm Dawid Budaszewski
Hello! I'm Dawid. I'm a full-stack developer with a couple of years of experience under my belt. I spent most of my career working with React. Now it's time to pass the knowledge onto somebody else!

💬 Leave a comment

Your email address will not be published.

We will never share your email with anyone else.