Here's how to force a re-render in React. ⚛
Tags: react, javascript, webdev, tutorial
Published: 2020-10-30 12:57:10

Hey there React developers! Do you struggle with unnecessary re-renders of components in your application?
 
We all must have gone through this phase when one component just keeps on updating its data in the background and then the overall performance takes a hit! 

Most of the time when you start optimizing the code to the best of your knowledge you can assume that it is a very complex and tiring process because everything in React happens so fast when it updates the DOM.

Also, the fact that the DOM was updated doesn't mean that it was actually modified by your changes. Well, then how do you stop this from happening or how would you rather force the Render? In this article, we're about to see exactly how.

![Force GIF](https://media.giphy.com/media/MrjMIWrGZFsTS/giphy.gif)
<figcaption>That's an impressive force!</figcaption>


---

# A quick note on Render 📝

> React's [`createElement()`](https://reactjs.org/docs/react-api.html#createelement
) function creates and returns a new element according to the element of the given type. 

Whether it's the `props` or the `children`, all the updates are done automatically only when it's needed. Based on what JSX we write for the DOM, React creates a virtual instance of it called the Virtual DOM. This whole process of updating the DOM always consists of the following three stages: 

1. [**Render**](https://reactjs.org/docs/react-dom.html#render
): this renders the React element into the DOM, returning a reference to the component. The output is taken from the `createElement` function.

2. [**Reconciliation**](https://reactjs.org/docs/reconciliation.html#gatsby-focus-wrapper): using the [Diffing Algorithm](https://www.cronj.com/blog/diff-algorithm-implemented-reactjs/), new elements are compared against previously elements and if there is a difference, the virtual DOM is updated.

3. Commit: finally, the stage where the real changes (DOM updation) are made. 

Let's see how the re-render is done in both the class and functional component types.

## Forcing a re-render in a class component

This is pretty straightforward. We can use the [**`forceUpdate()`**](https://reactjs.org/docs/react-component.html#forceupdate) function provided by the React API. It takes the following syntax:

```jsx
component.forceUpdate(callback)
```

This is highly useful when the rendering depends on some other data apart from the state and you need React to re-render that specific component. The process is achieved by skipping the [`shouldComponentUpdate()`](https://reactjs.org/docs/optimizing-performance.html#avoid-reconciliation) lifecycle Hook.
 
Now if you compare the [`setState`](https://reactjs.org/docs/faq-state.html#what-does-setstate-do) with `forceUpdate`, you will get to know that the latter will update a component even if the `shouldComponentUpdate` is implemented.

#### ⚠️ Pssst. Wait wait! There's a warning here though. You should try to avoid all uses of `forceUpdate()` and instead read from `this.props` and `this.state` in `render()`.

Now, what is the solution then?

### Re-render when state changes

Make use of the `render()` method and [`setState()`](https://reactjs.org/docs/react-component.html#setstate).

The whole purpose of `setState` is to add changes in the queue to the component's state and it tells React that this component and its children need to be re-rendered with the updated state. This takes in the following syntax:

```jsx
setState(updater, [callback])
```

Let's update the state of a component when it mounts.

```jsx
class App extends React.Component {
  componentDidMount() {
    this.setState({});
  }

  render() {
    console.log('Render is invoked')
    return <h1>Hi!</h1>;
  }
}
```

Here, we used the [`componentDidMount()`](https://reactjs.org/docs/react-component.html#componentdidmount) lifecycle Hook to update the state.

Another example is for an event in a component:

```jsx
class App extends React.Component {
  state = {
    msg: ""
  };

  handleClick = () => {
    this.setState({ msg: "Updated!" });
  };

  render() {
    console.log('Render is invoked');
    return (
      <>
        <button onClick={this.handleClick}>Click me</button>
        <div>{this.state.msg}</div>
      </>
    );
  }
}
```

In this case, with the click of a button, we update the state.

## Forcing a re-render in a functional component

Like in a class component, we don't have the flexibility to choose `forceUpdate`. But we can surely go close to it as much as we like to by using the concept of [**React Hooks**](https://reactjs.org/docs/hooks-intro.html).

Specifically, if we use the [`useState`](https://reactjs.org/docs/hooks-reference.html#usestate) Hook, for a simple counter app, where on the `onClick` of a button, we increase the previous count inside the setter function of `useState` (for example: `setCount`). This is exactly the point where we need to force the re-render of the counter component.

Here's a relatable example:

```jsx
import React, {useState} from ‘react’;

const App = props => {
    const [count, setCount] = useState(0)

    const onClickHandler = event = => {
        setCount(count => count + 1)
    }

    return (    
        <button onClick={onClickHandler}>Click me</button>
    )
}
```

You can even go ahead and write your own [custom Hook](https://reactjs.org/docs/hooks-custom.html) according to the need. It will work the same way just that this time you will have control over this Hook to add multiple points where you need a re-render.

---

# Where to next? 🤔

Make your re-render count by visiting the following resources that talk more about different case scenarios and examples:

📄 [React `render()` documentation](https://reactjs.org/docs/react-dom.html#render)

{% medium https://medium.com/weekly-webtips/force-component-to-re-render-with-hooks-in-react-c57cde48dc9f %}

{% stackoverflow 30626030 %}

---

_Thanks for reading, I appreciate it! Have a good day. (✿◕‿◕✿)_

---
<blockquote class="twitter-tweet" data-partner="tweetdeck"><p lang="en" dir="ltr">TIME TO GET TO WORK! 😀<br><br>Image source: <a href="https://t.co/t9tnTL53go">https://t.co/t9tnTL53go</a><a href="https://twitter.com/hashtag/DevHumour?src=hash&amp;ref_src=twsrc%5Etfw">#DevHumour</a> <a href="https://twitter.com/hashtag/SQL?src=hash&amp;ref_src=twsrc%5Etfw">#SQL</a> <a href="https://twitter.com/hashtag/BigData?src=hash&amp;ref_src=twsrc%5Etfw">#BigData</a> <a href="https://t.co/vblvcTRpqL">pic.twitter.com/vblvcTRpqL</a></p>&mdash; Microsoft Developer UK (@msdevUK) <a href="https://twitter.com/msdevUK/status/1321737294173343744?ref_src=twsrc%5Etfw">October 29, 2020</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
---

#### [📫 Subscribe to my weekly developer newsletter 📫](https://mailchi.mp/f59beeac6b9b/devupdates)

##### PS: From this year, I've decided to write here on DEV Community. Previously, I wrote on Medium. If anyone wants to take a look at my articles, [here](https://medium.com/@vaibhavkhulbe)'s my Medium profile.