Force a React Component to Re-Render

By  on  

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.

Recent Features

  • By
    Convert XML to JSON with JavaScript

    If you follow me on Twitter, you know that I've been working on a super top secret mobile application using Appcelerator Titanium.  The experience has been great:  using JavaScript to create easy to write, easy to test, native mobile apps has been fun.  My...

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Incredible Demos

Discussion

  1. I can’t think on a real case where this is useful. Can someone give examples?

    • One place I’ve heard this come up a bunch is the case where you’re using non-React widgetry inside React components.

    • In React Native, special kinds of values ie

      Animated

      are manipulated via a function call

      someAnimatedValue.setValue(someNumber)

      , which refreshes the value without updating the component State and, thereby, not triggering a re-render.

      this.forceUpdate()

      helps to trigger the re-render in this case.

    • At this moment I’m working on a kind of “manager” module to orchestrate behavior for stateless components. These behaviors are further separated into small modules. What would normally be tracked as state (and setState) is now the responsibility of a separate Model class in vanilla JS. I’m also building the manager as a React component, but in order to thread down the updated model to the stateless components it looks like forcing an update is the best way to go so far!

    • Aaron

      When I have a controlled component such as an Input element handle updating some data, the value will be using data from states. If I also need to delete a row on the UI, I want to force the app to refresh the data because otherwise there is no state changed.

    • I have a list of notifications including relative timestamps, ie. “About 20 seconds ago”. The actual state of the component technically doesn’t change as time progresses, so it stays stuck there. By forcing an update every few seconds you can see the timestamps go up to “About 30 seconds” etc.

    • I just used this with an SSR-enabled app in which I use components that can only be imported client-side. And so I needed something to trigger a rerender once the dynamic import had finished.

    • James

      Yes…. When another process outside of your react application updates your data and you need to see those changes on your screen, this use case is critical… think of real time systems such as industrial systems that display condition monitoring information or stock display systems that display stock prices.

    • Seyyed Arshia Siadati

      // android orientation
      // I couldn’t use {height: “100%”} because that View was placed in ScrollView

      this.forceUpdate()}
      />

  2. Dimitris Proios

    When using some other library that has logic that u cannot put in the parent component to update via props and setState on componentDid/WillUpdate will create update loop, it can be useful.
    Personnally I have used it in react virtualized library to update data that were not in props or state but in a component variable.

  3. Paul

    Totally wrong way to do this.
    the better way is to add a query param at the end of the image src. That works better than trying to forceupdate the component. Please disregard my comment above.

  4. Danny

    My use case for this comes from using Redux stores where I am passing store props to an external component, but this happens before I update the store from an XHR request, i.e. the local component mounts before it gets the new data.

    Even though UI elements get updated with the XHR response, the new store props are not being passed down to the external component. In order for that to happen I needed to use this.forceUpdate() which then passed the new store props to the external component to render the data and display on the local component.

    This worked great, thanks for the article!

  5. You can force rerender of component by simply updating it’s key

  6. Instead of this.setState({ state: this.state }); you could just write this.setState({});, but that will only trigger re-render is your component doesn’t implement shouldComponentUpdate (as, e.g., PureComponent).

  7. Nikhil D Thakkar

    Another situation would be wherein you want to add the components dynamically based on some user action.

  8. Bishop Eguabor

    another use case for the compoent to re render is when ur are creating switches for example you can you know state does you cant update your state more that once so that another use case for the component to re render

  9. Some Man

    Sorry, but this just won’t work.

    https://jsfiddle.net/igronus/ue01o6h9/

  10. BHV

    Awesome! This worked perfectly.

    I had an element wich content is edited with a Text Editor, the button “Save” is calling the next function.

        const saveContent = () => {
            const getTextEditorContent = myEditor.current.editor.getContents()
            let temporalData = data
            temporalData.home.content = textEditorContent
    
    //This doesn't re-render the element content
            setData( temporalData )
    
    //Your solution worked like charm
            setData({ ...data })
        }
    

    I’m using this because the data is stored in a very high nested JSON file, I’m forced to work in the Intranet of the company with access only to files and folders, so I had to improve my own database without Backend capabilities.

    Thank you very much <3

  11. Thanks for your article. Helped me with my issue almost immediately!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!