Force a React Component to Re-Render

The beauty of React components is that they automagically render and update based on a change in state or props; simply update the state from any place and suddenly your UI element updates — awesome!  There may be a case, however, where you simply want to brute force a fresh render of a React component.


Note:  In most cases you should never force a React component to re-render; re-rendering should always be done based on state or props changes.  Nonetheless, I don’t judge and there may be a case where you legitimately need to force a React component to re-render so let’s have it!


Force React Component Render


There are multiple ways to force a React component render but they are essentially the same.  The first is using this.forceUpdate(), which skips shouldComponentUpdate:



someMethod() {
    // Force a render without state change...
    this.forceUpdate();
}


Assuming your component has a state, you could also call the following:



someMethod() {
    // Force a render with a simulated state change
    this.setState({ state: this.state });
}


This blog doesn’t aim to be prescriptive, so I wont scold developers for using this brute force method.  Again, there’s likely a better, more “React-y” way to render a component properly, but if you are desperate to get a component render on command, there are many ways to do so with React.


  • Adding Events to Adding Events in MooTools

    Note: This post has been updated. One of my huge web peeves is when an element has click events attached to it but the element doesn’t sport the “pointer” cursor. I mean how the hell is the user supposed to know they can/should click on…

  • Assign Anchor IDs Using MooTools 1.2

    One of my favorite uses of the MooTools JavaScript library is the SmoothScroll plugin. I use it on my website, my employer’s website, and on many customer websites. The best part about the plugin is that it’s so easy to implement. I recently ran…

Leave Your Comment