@fazzaamiarso
Posted
Hello there! Great solution overall!
I found some critical problems in your code.
- You don't wrap the
addEventListener
inuseEffect
. Why it's problematic? the consequence of not attaching event listeners inuseEffect
is that you can't remove the listener after re-rendering. So, you are effectively attaching new listeners every render, which can slow down performance. Here is my improvement
useEffect(()=>{
// must create a separate function so it can be removed
const resizeFunction = () => {
if (window.outerWidth <= 768 && isLightBoxOpen) {
dispatch(toggleLightbox(-1, -1))
}
}
window.addEventListener('resize', resizeFunction)
return () => window.removeEventListener('resize', resizeFunction) //cleanup function
}, [dispatch, isLightBoxOpen])
- Mirrored props in a state. Here is the problematic state.
const [numberOfProduct, setNumberOfProduct] = useState(props.product.numberInCart)
Why it's a problem? because React won't re-initialize the state when props.product.numberInCart
changes in a re-render. So, you are at risk of having a stale state. But, if you just want it to be an initial state, that is not a problem. You can read more on the official docs about this specific problem.
Hope it's helpful! Goodluck!
Marked as helpful