DEV Community

ScorbicLife
ScorbicLife

Posted on

Escape Hatches

https://react.dev/learn/escape-hatches

Refs

  • Refs are values that
    • persist over renders (like state)
    • does not rerender the component (unlike state)

Ref attributes (which is a distinct concept from Refs)

  • ref attributes can be used on a builtin HTML tag can be used to get DOM nodes of the underlying element. e.g. <div ref={someRef} />
  • ref attributes can be used on a React component only if one creates the component with forwardRef.
  • You can also pass in a function to a ref attribute for custom behavior other than binding to a Ref. For example, <div ref={(element) => {}} />
  • ref attributes are used as an escape hatch for DOM manipulation that React cannot handle. Examples are
    • Non-destructive operations such as scrolling and focusing
    • Mutating part of the DOM that React never touches

Effects

  • There exists code that is...
    • neither a pure calculation, so cannot be run on rendering
    • nor is an event that has a trigger, so cannot be run in an event handler
  • Effects are side effects caused by rendering itself, not a particular event.
  • useEffect syntax is always as it has been.
    • Mind your cleanups so that your effects are idempotent.
  • useEffect trigger timings:
    • startup code runs on component mount or dependency change
    • cleanup code runs on component unmount or next dependency change

Personal Recap

Where to put data in React

  • Data does not persist between renders: use a local variable inside component
  • Data persists between renders:
    • On data update, should rerender: use state
    • On data update, should not rerender: use ref

Where to put code in React

  • Pure calculation
    • Put it inside a component to run it every render.
    • For optimization, cache it with useMemo.
  • Side Effect
    • If it's triggered because of an event, use an event handler.
    • If it's triggered because your component rendered, use an Effect.
      • e.g. syncing your component state with external code after render.
      • e.g. sending ajax requests because a component is rendered.

Top comments (0)