How to Force Re-Render a React Component & Should you do it?
Tags: react, javascript, webdev, tutorial
Published: 2021-10-17 05:06:33

**React** automatically **Re-Renders** the components whenever any of its **props** or its **state** is updated. But quite often beginners _(especially me in my early days)_ find it quite difficult getting a component **re-rendered**.

First, let's look at the _methods we can use to **re-render** a component_, and discuss _whether we should really force a **re-render**_ or let **React** take care of it.

# Re-Render a Class Component

**Class Components** provide you a **built-in method** to trigger a **Re-Render**. Simply use `forceUpdate` method to force **React** to **Re-Render** the component.

```js
class App extends React.Component{
  constructor(){
    super();
    this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
  };
  
  forceUpdateHandler(){
    this.forceUpdate();
  };
  
  render(){
    return(
      <div>
        <button onClick={this.forceUpdateHandler}>
          Change Number
        </button>
        <h4>Random Number : { Math.random() }</h4>
      </div>
    );
  }
}
```

# Re-Render a Functional Component

Unfortunately, **Functional Component** doesn't have a `forceUpdate` method for ease of use. You can use `useState` hook to simulate an update or create a **custom hook** too.

```js
// forceUpdate hook
function useForceUpdate() {
  const [value, setValue] = useState(0);
  return () => setValue((value) => value + 1);
}

// component
function App() {
  const forceUpdate = useForceUpdate();

  return (
    <div>
      <button onClick={forceUpdate}>
        Change Number
      </button>
      <h4>Random Number : { Math.random() }</h4>
    </div>
  );
}
```

# Should you Force Re-Render a React Component?

Now for answering the most important question...

### **NO! NO! and NO!!!!!!!!!!**

![No](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/erjatgj9qpcfzvjde116.gif)

In most cases, you DEFINITELY SHOULD NOT **force a re-render**! 

There are a few _niche cases_, like **modifying a blockchain** (which only returns a **transaction hash** and no data), where the **forced re-render** makes sense to _fetch the updated data_ from the **blockchain**.

# Debugging Why the Component isn't Updating

Let's look at some of the common issues why _**React** fails to update your components_ and _find solutions for them as well_.

## 1. Incorrectly Updated State

Let's consider the following example:

```js
const App = () =>  {
  const [user, setUser] = useState({ name: "", age: 0, });

  const updateUser = () => {
    user.name = "Tom";
    setUser(user)
  }

  return (
    <>
      <h2>Name: {user.name}</h2>
      <button onClick={updateUser}>
        Update User
      </button>
    </>
  );
}
```

The `App` component would not be **re-rendering** the _user's name_ even when the `Update User` button is clicked.

**React** evaluates state changes by checking its **shallow equality** (also called **reference equality**), which checks to see if _both the current and the new value for state reference the same object_. In our example, we updated one of the properties of the **user object**, but we technically made `setUser` the same object reference, and thus, **React** _didn’t perceive any change in its state_.

As [**React** documentation](https://reactjs.org/docs/react-component.html#state) mentions, _State should be treated as immutable_.

So, how do we fix it? We could _create a new object with the updated values_:

```js
  const updateUser = () => {
    setUser({
      ...user,
      name: "Tom",
    })
  }
```

## 2. Incorrectly Updated Props (without state change)

Incorrectly updating props without a state change can also leads to bugs. Let’s look at an example:

```js
let time = new Date();
// setInterval(() => {
//   console.log(time)
// }, 1000);

const App = () =>  {
  useEffect(() => {
    const intervalId = setInterval(() => {
      time = new Date()
    }, 1000);
    return () => clearInterval(intervalId);
  }, []);

  return (
    <Clock time={time} />
  );
}
```

The `Clock` in the example doesn't update the `time` after the first load. To confirm that the `time` is being properly updated, you can just un-comment the `console.log`. Every second, _the runtime will update the variable `time`, which is then passed to our `Clock` component for rendering_.

When the state changes, `App` (parent component) is **re-rendered**, thus triggering a **re-rendered** in `Clock` (child component) with the updated `time`. Thus _updating state is what actually triggers the re-render_, which is then _propagated through the props_. So updating the state is ABSOLUTELY CRUCIAL!

So to fix the issue, we could use the following:

```js
const App = () =>  {
  const [time, setTime] = useState(new Date());
  useEffect(() => {
    const intervalId = setInterval(() => {
      setTime(new Date());
    }, 1000);
    return () => clearInterval(intervalId)
  }, [])

  return (
    <Clock time={time} />
  );
}
```

# Wrapping up

Just like everything in this world, this article too has to end 😛 

In the article, we went through some of the ways you can **force re-render** your **React** Components as well as the common causes of why _**React** fails to re-render the components_. Hope this helps you.

**Best of Luck with your React Development Journey!**

Finding **personal finance** too intimidating? Checkout my **Instagram** to become a [**Dollar Ninja**](https://www.instagram.com/the.dollar.ninja/)

# Thanks for reading

Need a **Top Rated Front-End Development Freelancer**? Contact me on [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)

Want to see what I am working on? Check out my [GitHub](https://github.com/ruppysuppy)

I am a freelancer who will start off as a **Digital Nomad** in mid-2022. Want to catch the journey? Follow me on [Instagram](https://www.instagram.com/tapajyotib/)

Follow my blogs for **Weekly new Tidbits** on [Dev](https://dev.to/ruppysuppy)

**FAQ**

These are a few commonly asked questions I get. So, I hope this **FAQ** section solves your issues.

1. **I am a beginner, how should I learn Front-End Web Dev?**
    Look into the following articles:
    1. [Front End Development Roadmap](https://dev.to/ruppysuppy/front-end-developer-roadmap-zero-to-hero-4pkf)
    2. [Front End Project Ideas](https://dev.to/ruppysuppy/5-projects-to-master-front-end-development-57p)

2. **Would you mentor me?**
    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

3. **Would you like to collaborate on our site?**
    As mentioned in the _previous question_, I am in a time crunch, so I would have to pass on such opportunities.

**Connect to me on**

-   [LinkedIn](https://www.linkedin.com/in/tapajyoti-bose/)
-   [Portfolio](https://tapajyoti-bose.vercel.app)
-   [Upwork](https://www.upwork.com/o/profiles/users/~01c12e516ee1d35044/)
-   [GitHub](https://github.com/ruppysuppy)
-   [Instagram](https://www.instagram.com/tapajyotib/)