I have a react component that consists in an alert to which I am passing 2 props, (however these 2 props rarely change within this component)
const AlertPopUp = ({ severity, errors }) => {
const [show, setShow] = useState(true)
console.log('show value of show state: ', show)
useEffect(() => {
console.log('gets here')
const timeId = setTimeout(() => {
// After 5 seconds set the show value to false
setShow(false)
}, 5000)
return () => {
clearTimeout(timeId)
}
});
console.log('errors ', errors)
if (!errors) return null
if (show)
return (
<>
<Alert severity={severity}>
{errors}
</Alert>
</>
)
}
In the first render, the Alert
shows up and after the expected 5 seconds the component disappears.
In the re-render, the Alert
does not show up anymore, and from my debugging I assume it has to do to with the line console.log('show value of show state: ', show)
which displays false in the re-render.
If I do a setShow(true)
I run into an infinite loop of re-renders.
If I use a useRef
to avoid the useState
infinite loop the component doesn't re-render and therefore the Alert
never displays.
If I try to set a key to the component key=useId()
/ pass a counter , the state is still set to false whenever the parent component rerenders, looking like the component doesn't destroy and create again.
Please forgive me if I made any of my assumptions wrongly as I am far from being a react expert.
Could please anyone help me find a solution so that the Alert
displays in every render of the alert component and disappears after the 5 seconds?
from react component displaying in first render but not in the following re-render
No comments:
Post a Comment