javascripthtmlreactjsnext.js

How do I stop reactjs from re-rendering the page when the user tabs out?


Very general question: I have a relatively simple react/nextjs page with a graph interface on it. Every time I change tab on Firefox and revisit the page, the page will re-render and cause the interface to reset. How can I stop this? I have tried using memos on the relevant components but to no avail.

Edit with some code snippets, some variable names have been censored:

This is a memo containing a switch which returns the contents based on the variable 't'.

const PageContents = memo(function PageContents({t}) {
    console.log("re-rendering the page contents...")
    switch(t) {
    case "graph":
        console.log("graph tab")
        return(
        <>
        <Graph data={data}/>   
        </>
        )
    ...other cases...
});

Return:

return (
<>
    <Helmet>
         <title>Title</title>
    </Helmet>
    <MenuAppBar position="absolute"/>
    <Container component="main" maxWidth={false} >
    <Stack direction={"row"} justifyContent={"space-between"}>
        <Box pt={3} display={"flex"}>
            <Typography variant="h4">
            Schema: {schema}
            </Typography>
        </Box>
        <TabBar/>
    </Stack>
    <BasicBreadcrumbs/>
    <PageContents t={tab}/> //'tab' comes from router.query
    </Container>
</>
)

Solution

  • I solved this by removing all the unused useState()s at the top of the component.

    edit: In hindsight, what may have been happening here was related to my authorisation logic. It wasn't properly set-up and would generate a new token everytime the user focused the window (because of a similar useState issue). After fixing the authorisation, this problem was fixed on other pages as well. I don't know why removing the useState() from PageContents fixed it in this case, but I can only guess that is was some interaction between the authorisation useStates and the PageContents useStates.