Home > Enterprise >  useRef value reinitialising on re render
useRef value reinitialising on re render

Time:07-21

import AccordionSummary from '@mui/material/AccordionSummary';
import DirectionsBusIcon from '@mui/icons-material/DirectionsBus';
import DirectionsWalkIcon from '@mui/icons-material/DirectionsWalk';
import { Box } from "@mui/material";
import { useRef } from 'react';

const RouteSummary = (props) => {

    const expanded = useRef(0)

    const handleClick = ()=>{
        expanded.current  
        props.onClick()
    }
    console.log("testing",expanded)

    return(
        <AccordionSummary expanded ={expanded} onClick = {handleClick} key={Math.random()}
        aria-controls="panel1a-content"
        sx={{width:"100%",display:"flex",paddingLeft:"2rem"}}
        >{props.routeObj.map((stepObj) =>{
            return <Box key={Math.random()} sx={{display:"flex"}}>
            {stepObj.mode==="WALKING"?<DirectionsWalkIcon/>:<DirectionsBusIcon/>} {stepObj.busNumber?
            <Box sx={{backgroundColor:"#FBCB0A",marginRight:"0.5rem",borderRadius:"5px",padding:"0.2rem"}}>
                {stepObj.busNumber}
                </Box>:null}
            </Box>}).reduce((prev, curr) => [prev, ' > ', curr])}
        </AccordionSummary>
    )
}

export default RouteSummary;

The value of expanded changes back to zero after a rerender which I cannot understand. I know that useRef should persist across renders so I don't understand this behaviour.

CodePudding user response:

Your problem was this:

key={Math.random()}

you likely used this also on parent components. When reacts reconciliation algorithm encounters a different key on next render for the same component on same spot in component hierarchy, it will unmount the component and mount new one - that's why the useRefs value was being lost too.

That's why using Math.random() as a key is usually bad idea.

  • Related