Sub topic 3
Referential equality: when two values count as the same
React decides whether to skip work by comparing values from one render to the next. This chapter explains how that comparison works. It is the base for React.memo, useMemo, useCallback and dependency arrays in the chapters that follow.
Prerequisites
This chapter assumes you know:
- Function components and JSX.
- The
useStatehook. - How props pass from a parent to a child.
- That JavaScript objects, arrays and functions are reference values.
Primitives and references
JavaScript has two kinds of values.
- Primitives are numbers, strings, booleans,
null,undefined, symbols and bigints. They are compared by their content. The number5is the same as any other5. - Reference values are objects, arrays and functions. A variable holds a pointer to a place in memory, not the content. Two variables are equal only if they point to the same place.
console.log(5 === 5); // true
console.log('a' === 'a'); // true
console.log({ a: 1 } === { a: 1 }); // false
console.log([1] === [1]); // false
console.log((() => {}) === (() => {})); // false
const user = { name: 'Ada' };
const same = user;
console.log(user === same); // trueThe two object literals have identical content, yet each one creates a new object in memory. That is why they are not equal. This is referential equality: two reference values count as the same only if they are the very same object.
Object.is, the comparison React uses
React does not use === directly. It uses Object.is. For almost every value the two give the same answer. They differ in two cases.
| Expression | `===` | `Object.is` |
|---|---|---|
| `NaN` and `NaN` | `false` | `true` |
| `0` and `-0` | `true` | `false` |
| `{}` and `{}` | `false` | `false` |
| Same object and itself | `true` | `true` |
The NaN difference is useful. A state value of NaN does not look like a change on every render. The -0 case rarely matters in practice.
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(0, -0)); // false
console.log(Object.is({}, {})); // falseWhere React applies this comparison
React uses Object.is in three places that matter for performance.
- State updates. If you call a setter with a value that is
Object.is-equal to the current state, React can skip re-rendering that component. - Props in
React.memo. React compares each prop of the new render with the same prop of the previous render. If every one is equal, it reuses the previous output. - Dependency arrays. In
useMemo,useCallbackanduseEffect, React compares each dependency with its previous value.
In all three, the comparison is shallow. React checks the value itself, and it does not look inside it. An object with the same fields but a different identity counts as changed. An object with the same identity but mutated fields counts as unchanged.
Why this matters during rendering
A function component runs again on every render. Everything declared inside it is created again, too. Objects, arrays and functions get a new identity each time, even when their content is identical.
function Profile({ userId }) {
// Each call to Profile creates a new object, a new array and a new function.
const style = { color: 'blue' };
const ids = [userId];
const handleClick = () => console.log(userId);
return <Child style={style} ids={ids} onClick={handleClick} />;
}If Child is wrapped in memo, React compares style, ids and onClick with the previous render. All three are new references, so the comparison fails and Child renders again. The memoization has no effect.
The next diagram shows how one render produces the same or different values.
A worked example
This component logs each time Chart renders. Clicking the button changes count, which re-renders Dashboard.
import { memo, useState } from 'react';
const Chart = memo(function Chart({ options, title }) {
console.log('render chart');
return <div>{title}: {options.color}</div>;
});
export function Dashboard() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Chart title="Sales" options={{ color: 'blue' }} />
</>
);
}On each click, title is the string "Sales". That is a primitive with the same content, so it counts as equal. options is a fresh object from the literal { color: 'blue' }, so it counts as changed. Because one prop differs, Chart renders on every click even though its output does not change.
One way to fix this is to create the object once, outside the component.
import { memo, useState } from 'react';
const Chart = memo(function Chart({ options, title }) {
console.log('render chart');
return <div>{title}: {options.color}</div>;
});
// Created once when the module loads, so the identity never changes.
const chartOptions = { color: 'blue' };
export function Dashboard() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Chart title="Sales" options={chartOptions} />
</>
);
}Now options points to the same object on every render, and Chart is skipped after the first one. Moving a constant value out of the component is the simplest way to get a stable reference. It only works when the value does not depend on props or state. Later chapters cover useMemo and useCallback for values that do.
Mutation and the opposite problem
Identity can also hide a real change. If you mutate an object and pass the same object back, React sees equal references.
import { useState } from 'react';
export function Counter() {
const [state, setState] = useState({ count: 0 });
function increment() {
state.count += 1; // Mutates the existing object.
setState(state); // Same reference, so React skips the update.
}
return <button onClick={increment}>Count: {state.count}</button>;
}The screen does not update, because Object.is(state, state) is true. The fix is to create a new object.
import { useState } from 'react';
export function Counter() {
const [state, setState] = useState({ count: 0 });
function increment() {
setState({ ...state, count: state.count + 1 });
}
return <button onClick={increment}>Count: {state.count}</button>;
}The rule is symmetrical:
- Create a new reference when the content changes.
- Keep the same reference when the content has not changed.
The first half is a correctness rule, because the UI will not update without it. The second half is a performance rule, because memoization will not work without it.
Common mistakes
- Comparing by content in your head. Two values that look identical in the code can be different references. Ask whether they come from the same creation, not whether they look alike.
- Assuming a deep comparison.
memoand dependency arrays never inspect nested fields. A change inside a nested object is invisible unless the outer object is replaced. - Creating values in the render body and passing them to memoized children. Object literals, array literals, inline arrow functions, and results of
.map()or.filter()all produce new references each render. - Using a value in a dependency array that is rebuilt every render. The hook then reruns every time, which wastes work and can cause loops in effects.
- Believing a stable reference always helps. It helps only when something downstream compares it. Stabilizing a prop on a component without
memochanges nothing.
Checking identity while debugging
You can check whether a value is stable by keeping its previous version in a ref and comparing. This is a debugging aid and not something to ship.
import { useRef } from 'react';
export function useIdentityLog(name, value) {
const previous = useRef(value);
if (!Object.is(previous.current, value)) {
console.log(`${name} changed identity`);
}
previous.current = value;
}Call useIdentityLog('options', options) inside a component. If the message prints on every render, the value is being recreated. Writing a ref during render is acceptable here only because this is temporary diagnostic code. The React DevTools Profiler, covered in an earlier chapter, can also show which props changed.
Summary of the rules
| Situation | Result of the comparison |
|---|---|
| Same primitive content | Equal |
| Same object, mutated | Equal, so a change is missed |
| New object, same fields | Not equal, so work is repeated |
| Same function declared once | Equal |
| Function declared in the render body | Not equal on each render |
| `NaN` and `NaN` | Equal under `Object.is` |
Exercise
In the component below, Row is wrapped in memo. Why does Row still render every time the user types in the input, and what is the smallest change that stops it?
const Row = memo(function Row({ tags }) { return <li>{tags.join(', ')}</li>; });
function List() {
const [text, setText] = useState('');
return (
<>
<input value={text} onChange={(e) => setText(e.target.value)} />
<Row tags={['a', 'b']} />
</>
);
}
Show answer
Each render of List evaluates the array literal ['a', 'b'], which creates a new array. memo compares tags with Object.is, sees a different reference, and renders Row again. The smallest fix is to move the array out of the component, for example const tags = ['a', 'b']; at module level, and pass tags={tags}. The reference is then the same on every render, so memo skips Row.
Exercise
A component calls setItems(items) after running items.push(newItem) on the state array. The list on screen does not update. Explain why, and write the corrected update.
Show answer
push mutates the existing array, so items keeps the same identity. React compares the new state with the old using Object.is, finds them equal, and skips the update. Create a new array instead: setItems([...items, newItem]);. The new reference lets React see the change.
Exercise
What does Object.is(NaN, NaN) return, and how does that differ from NaN === NaN?
Show answer
Object.is(NaN, NaN) returns true, while NaN === NaN returns false. React uses Object.is, so a NaN value in state or in a dependency array is treated as unchanged between renders.