Refresh page before rendering component in React app

725 views Asked by At

I have similar problem as in Refresh the page only once in react class component.

There are several pages in my application and I move between them using BrowserRouter and useNavigate (react-router-dom v6). One of pages has greater size div and when I go back to main page, it's(main's) css gets messed up(button position changes, some media file grows out of divs, hovers are not displayed) until I refresh page(main page). As soon as I refresh page, everything sets up well. I used code snippet provided by @rommyarb in the link above. It works, but there is time delay (less 1sec, still visible). Which means when we navigate back(navigate(-1)), it first renders mainpage with broken css --> (0.2-0.5s) then it refreshes and css is recovered.

Time delay is not big, but still it would be unpleasant user experience. Is there any way to first refresh page (localhost/main) then render component with proper css.

Any help would be appreciated!

Code:

function App() {

  return (
    <Router>
      <Routes>
        <Route exact path='/' element={<MainPage props ={props}/>} />
        <Route path='/UnderConstruction' element={<UnderConstruction/>}/>
      </Routes>
    </Router>
  )
}


function UnderConstruction(props) {
    let navigate = useNavigate();
    return (
        <div className='UnderConstruction' style={somestyles}>
                <h2>This page is under construction</h2>
                <div style={somestyles}>
                <img src={under_construction.jpg'} width="100%" height="60%" />
                <Button style={somestyles} onClick={() => {
                    navigate(-1)
                    }}> Go Back</Button>
                </div>
        </div>

    );
1

There are 1 answers

0
shinixxhi On

I solved problem. The makeStyles return function(hook), when we call it within component, we can access only styles naming, which is string. So, every time we call a function, naming changes (makeStyles-element-number) due to global counter. I saved styles in state, which saved only string name. After re-rendering actual styles name was changed(makeStyles-element-number incremented) and the one I saved mismatched with actual styles. The simple solution was not storing makeStyles styles in state.

For more details read: Internal implementation of "makeStyles" in React Material-UI?