When to use forceUpdate() in React ⚛
Tags: javascript, webdev, react, tutorial
Published: 2021-02-01 17:21:39

As the name suggests FORCE 🏋🏼‍♀️ is any interaction that, when unopposed, will change the motion of an object (*from Wikipedia*).

Force is something that we apply to things that are not usually intended to do. We have to use force smartly It could also harm you. 

You will not encounter to use this react API usually. But I am writing this blog because I just used this at my work. And this article gives you a hint that where you can use forceUpdate. There are so many things in tech which you will not use in day to day life but you have to learn by which it will click into your mind 💡 whenever you truly need.

> Disclaimer:  Don't use forceUpdate until and unless you know what you are doing. As react suggest use state or props which will automatically handle all renders.


# What is forceUpdate

In react, components will automatically re-render themselves when props or state change.
However, there are some scenarios in which render depends on some other data in which We have to tell react to re-render component forcefully. 

For this There is an API in react called [forceUpdate()](https://reactjs.org/docs/react-component.html#forceupdate).

Whenever you call forceUpdate on any component react will re-render and skip `shouldComponentUpdate` life cycle method because it could be a reason to prevent render in the component. For child components react will not prevent any method on them.

# Why not to use

- React skip `shouldComponentUpdate` life cycle method which eventually affects the performance especially in PureComponent 
- It is an anti-pattern.
- Harder to maintain (You can understand but your colleagues don't 😑or future developers).
- It's harder to predict the next state. 
- Pollute the previous state value so can't use of `shouldComponentUpdate/componentWillUpdate/componentDidUpdate` for comparison. 

## Implementation

As we all moved to functional component from class component unfortunately there is no such direct react API which will provide us force re-renders.

But We can achieve the same functionality by using the `useState` hook. There are also some different approaches to this you can check  [here](https://stackoverflow.com/questions/46240647/react-how-to-force-a-function-component-to-render).

Let's jump into an example.

## Example

Consider a problem in which we have table data and with each click of table row, we have to get some other details based on that row data.

Let's see the full code first
{% codesandbox react-table-expandcollapse-row-mx3gl %}
 

Here We have table data

```jsx
const data = [
  {
    company: "Alfreds Futterkiste",
    contact: "Maria Anders",
    country: "Germany"
  },
  {
    company: "Centro comercial Moctezuma",
    contact: "Maria Anders",
    country: "Mexico"
  }
];
```
Looping through this and make a table is not a big deal if you are familiar with react.
But as you can see we have to expand and collapse the table row and inject data that we don't currently have (This is my approach to deal with this problem. You can suggest me another approach in the comments 🤗).

If you have some knowledge about react it uses the concept of functional programming. And due to this, we should follow the rule of immutability. Which you can't be modified after being instantiated.

Here react will not re-render itself by changing table data object directly. And finally, here we can use force update or useState as I showed in code. It will tell react to re-render the component.

```jsx
const [state, setState] = useState(0);

 const handleClick = (index) => {
    const updatedState = data[index];

    if (updatedState.other) {
      delete updatedState.other;
      setState((pre) => {
        return pre + 1;
      });
    } else {
      updatedState.other = {
        description: "Hello there"
      };
      setState((pre) => {
        return pre + 1;
      });
    }
  };

```

`handleClick` is an event handler that takes clicked row index and mutates table data object. Here useState works as `forceUpdate`.I have simply used counter which will set a new incremental state after every setstate.


Thanks for reading. Thanks, me when it clicks in the future 🤝.