1

I'm looking for a way to have React not render a component if the page was just loaded or refreshed. The component should only render if the user is browsing from page to page within the single-page application.

I've tried using window.document.readyState to detect this but that's been hit or miss.

1 Answer 1

2

You could use Session Storage in the browser like this

if(!sessionStorage.active || sessionStorage.active == window.location.href) {
    // First visit or refresh
} else {
    // Render component
}
sessionStorage.active = window.location.href;

When the user first visits the page, sessionStorage.active will not be set and it will go to // First visit or refresh.

If the user refreshes the page, sessionStorage.active will be set but it will also equal the current url and go to // First visit or refresh.

If the user visits the page from another page within the site, sessionStorage.active will be set and it won't match window.location.href since it's currently set to the previous visited pages url. Therefore it will go to // Render component.

There might be some quirks with this solution that has to be solved for special use cases, but hopefully you have a good starting point.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.