How to Refresh Pages in React With One Line of Code
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>
)
}
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>
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.
Unlimited access to hundred of tutorials
Access to exclusive interactive lessons
Remove ads to learn without distractions