HomeToolsAbout

Render

Re-rendering Rule

React re-renders on every state change

Every state change triggers a re-render, but not when state object is deeply compared to.

React doesn't do deeply equal comparison on state object changes

It only checks if the instance of the object has changed.

  • You are always better off passing a 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});

Alternative to Object Copy: new state for re-trigger

Caveat that creating a copy of object or array may become expensive

  • An easy trick to trigger an update instead of creating a copy of the state is to add a state to trigger React to render on update
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()); ... }

Conditional View Component Render

Using && to replace an if statement without else

&& is a null check

  • It works like a single if statement without else
  • It returns the first falsy value, if none then it returns the last operand
  • Use this for conditional rendering instead of rendering an empty JSX <></> on falsy ternary check
// do this isNullCheck && ( <ConditionalRender /> ) // not this if (isNullcheck){ <ConditionalRender /> } else { <></> }
AboutContact