Every state change triggers a re-render, but not when state object is deeply compared to.
deeply equal comparison
on state object changesIt only checks if the instance
of the object has changed.
new copy
of a state object to guarantee a re-render
.const updatedObject = {}; updatedObject.field = "new value"; // state change won't trigger re-render setObject(updatedObject); // copy of an object is created, guaranteeing update/re-render 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 { <></> }