ReactMedium

What is referential equality?

Referential equality means two values are the same reference in memory, checked with === or Object.is. For objects, arrays and functions, two values with identical contents are not equal unless they are the same reference. React relies on it for dependency arrays, memo, context values and state bail-outs.

Primitives vs references

  • Primitives compare by value: "a" === "a", 1 === 1.
  • Objects compare by reference: {} === {} is false, [1] === [1] is false, (() => {}) === (() => {}) is false.
  • Object.is is like === but treats NaN as equal to itself and +0/-0 as different. React uses Object.is.

Where it matters in React

  • Dependency arrays: an object or function created during render is new every render, so effects re-run every time.
  • React.memo: new object or function props make shallow comparison fail, so the child re-renders.
  • Context: value={{ user, logout }} is a new object on every provider render, re-rendering all consumers.
  • State updates: setState(sameObject) bails out; mutating an object and setting it again is ignored because the reference did not change. That is why you must create new objects for updates.

Getting stable references

  • Define constants and pure functions outside components.
  • Move objects and functions into effects.
  • useMemo and useCallback, or the React Compiler.
  • Depend on primitive fields (user.id) instead of objects.
  • Keep immutable updates so changed data gets a new reference and unchanged data keeps its old one.

Code example

tsx
1import { memo, useMemo, useState } from "react";
2
3console.log({} === {}); // false: different references
4const a = { x: 1 };
5const b = a;
6console.log(a === b); // true: same reference
7console.log(Object.is(NaN, NaN)); // true
8
9const Child = memo(function Child({ options }: { options: { compact: boolean } }) {
10 console.log("Child render");
11 return <p>{options.compact ? "Compact" : "Comfortable"}</p>;
12});
13
14export function Parent() {
15 const [count, setCount] = useState(0);
16 const [compact, setCompact] = useState(false);
17
18 // New object every render: memo is defeated
19 // const options = { compact };
20
21 // Stable until `compact` changes
22 const options = useMemo(() => ({ compact }), [compact]);
23
24 return (
25 <>
26 <button onClick={() => setCount((c) => c + 1)}>Re-render parent ({count})</button>
27 <button onClick={() => setCompact((c) => !c)}>Toggle compact</button>
28 <Child options={options} />
29 </>
30 );
31}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app