How to Refresh Pages in React With One Line of Code

Using Vanilla JavaScript
Ferenc Almasi β€’ 2022 September 12 β€’ πŸ“– 1 min read

To refresh a page in React, you don't need React, just plain JavaScript. You need to call window.location.reload which will trigger a full page reload.

export const App = () => {
    const refresh = () => window.location.reload(true)

    return (
        <button onClick={refresh}>Refresh</button>
    )
}
Refresh function in React
Copied to clipboard!

This works exactly like a refresh button. Notice that we passed true to the reload method. This is a non-standard feature that is only supported in Firefox. It tells the browser to bypass the cache and do a force reload.

Using a boolean parameter for location.reload is ignored for all other browsers, except Firefox.

The same can be done using an inline onClick handler in the following way:

<button onClick={() => window.location.reload(true)}>Refresh</button>
Copied to clipboard!

However, in most cases, you may simply want to update your state instead of doing an entire page reload using useState. This results in a better user experience. Therefore, only use the above solution when you specifically want to do a full-page reload.

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended