Your React app is not re-rendering? Let’s fix that!

 

If you are new to React it can be so so frustrating when the code seems like it should work, but nothing is updating on the screen. There is no need to post to Stack Overflow for help and wait for hours for a response as you can normally fix these sorts of problems yourself in a minute or two. I’ll show you how.

Let’s say we have a simple React app – a counter and a button. Click the button and the counter goes up by one.

Here is some example code:

const { useState } = React;

const Counter = ({ count }) => {
  const [newcount, setCount] = useState( count )
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  )
}

ReactDOM.render(<Counter count={0} />, document.getElementById('app'))

It has a bug though!

Sadly, when you click the “Click Me” button, the number will not increment. Something is broken.

How can you fix this?

My recommended way for beginners is to use `console.log` which allow you to see updates in the debugger window as your code runs.

By adding this in a new line just before the return statement:

console.log(newcount)

You will be able to see what the value of the state is each time the render function is called. The render function being the entire function above defined for Counter. To see the `console.log` results, press F12 in your browser, open the developer tools and select the console tab.

You can now, like a detective, narrow down your suspect, and find exactly where the problem occurs and fix it quick.

If the console log shows the number you expect, then the state is correct! So where is the problem? Most likely in the JSX code after the return statement, it must be not using the state as you would expect.

If the number is incorrect, then the state is wrong, check the places where state is set, and your problem. This is most likely in places such as the click handlers.

As it turns out, in the example above, the problem is we are referring to the prop `count` instead of the `newcount` state in both the text we display and the click handler. There are two bugs. Both could be found by using the `console.log` method.

Try this in your React code today, even if you don’t have a problem. It is a useful tool to understand how your app is behaving “behind the scenes” – then when you need to fix a bug in your application for real, you will be more than ready.

Posted by Martin Capodici

.

Leave a Comment

Your email address will not be published. Required fields are marked *