Home > database >  In React.js, how can I prevent re-render on hard refresh?
In React.js, how can I prevent re-render on hard refresh?

Time:10-28

I have a main menu with 4 pages. If I do a hard refresh when I am on any of the pages, React takes me back to the page 1 screen. I want the user to stay on the same page when hard refresh happens.

Main Menu

  1. page 1
  2. page 2
  3. page 3
  4. page 4

I'm thinking useRef would be helpful, though I don't know how to structure the logic. Ideas are most appreciated!

CodePudding user response:

Nothing you store as React state persists page refreshes. The LocalStorage Browser API exists to solve this problem.

The localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. MDN

You could implement something like that in react with a custom hook like useLocalStorage that behaves similarly to useState, except that it will persists across page-refreshes using LocalStorage.

// persists across page loads
const [currentPage, setCurrentPage] = useLocalStorage('page-name')

CodePudding user response:

There's a package named react-router-dom which enables you to have routes in your reactjs apps that relates to the url, you can also achieve this without using this package but it would be wiser to use the package. Here's an example of it:

import { HashRouter as Router, Route, Switch } from 'react-router-dom';

// Components
import Homepage from './components/Homepage';
import AboutMe from './components/AboutMe';
import Error404 from './components/Error404';

export default function App() {
    return (
        <Router>
            <Switch>
                <Route key="homepage" exact path={['/', '/homepage']}>
                    <Homepage />
                </Route>

                <Route key="aboutme" exact path="/aboutme">
                    <AboutMe />
                </Route>

                <Route path="*">
                    <Error404 />
                </Route>
            </Switch>
        </Router>
    );
}

Using this package will not only make it so that the page doesnt change after a hard refresh, it will also make sure that theres a direct url to the page (assuming its not a authorized route/page). And if you would like to implement this on your own instead of using the package, this article can help you accomplish that

  • Related