Every state change triggers a re-render, but not when state object is deeply compared to
It only checks if the instance of the object has changed
// won't re-render const updatedObject = {}; updatedObject.field = "new value"; setObject(updatedObject); // copy of an object is created after update const updatedObject = {}; updatedObject.field = "new value"; setObject({...updatedObject});
Caveat that creating a copy of object or array may become expensive
const NewComponent = () => { const { setOpenModal, cart, setCart } = useContext(CartContext); const { lastUpdate, setLastUpdate } = useState(0); function increaseQuantity(product: number) { ... setLastUpdate(Date.now()); ... } function decreaseQuantity(product: number) { ... setLastUpdate(Date.now()); ... }
&&
to replace an if
statement without else
&&
is a null
check
if
statement without else
falsy
value, if none then it returns the last operand<></>
on falsy ternary check// do this isNullCheck && ( <ConditionalRender /> ) // not this if (isNullcheck){ <ConditionalRender /> } else { <></> }