HomeToolsAbout a20k

Render

Rendering Behavior

Development Strict Mode

  • React renders the page twice by default when in strict mode in development
    • Not in production
  • You should NOT turn off the strict mode to get rid of this behavior in dev

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 deep equal comparison on state object changes

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});

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 { <></> }
© VincentVanKoh