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:
{} === {}isfalse,[1] === [1]isfalse,(() => {}) === (() => {})isfalse. Object.isis like===but treatsNaNas equal to itself and+0/-0as different. React usesObject.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.
useMemoanduseCallback, 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";23console.log({} === {}); // false: different references4const a = { x: 1 };5const b = a;6console.log(a === b); // true: same reference7console.log(Object.is(NaN, NaN)); // true89const Child = memo(function Child({ options }: { options: { compact: boolean } }) {10 console.log("Child render");11 return <p>{options.compact ? "Compact" : "Comfortable"}</p>;12});1314export function Parent() {15 const [count, setCount] = useState(0);16 const [compact, setCompact] = useState(false);1718 // New object every render: memo is defeated19 // const options = { compact };2021 // Stable until `compact` changes22 const options = useMemo(() => ({ compact }), [compact]);2324 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.