DEV Community

Cover image for When to use forceUpdate() in React βš›
Harshil Parmar
Harshil Parmar

Posted on • Updated on • Originally published at harshilparmar.hashnode.dev

When to use forceUpdate() in React βš›

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().

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.

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

Here We have table data

const data = [
  {
    company: "Alfreds Futterkiste",
    contact: "Maria Anders",
    country: "Germany"
  },
  {
    company: "Centro comercial Moctezuma",
    contact: "Maria Anders",
    country: "Mexico"
  }
];
Enter fullscreen mode Exit fullscreen mode

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.

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;
      });
    }
  };

Enter fullscreen mode Exit fullscreen mode

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 🀝.

Top comments (0)