Pattern Components Beginner
Pure Component
A pure component produces the same output for the same inputs and doesn’t change anything outside itself while it renders, so the framework can safely reuse its last output, and tests are predictable.
The problem
Your component might show one thing on one render and something different on the next, even though its props are exactly the same. It might check the current time during render, or send an analytics event, and you can’t predict what it’ll do next.
The pattern
A pure component works like a pure function, so given the same inputs, it produces the same output every time. During render, it doesn’t use global state, check the current time, generate random values, or cause side effects. A side effect is anything the component does besides returning its UI, such as sending a request, writing to storage, or logging an analytics event.
Problem
If a component checks the time or generates a random value during render, your tests might pass some of the time and fail the rest, and the framework can’t safely skip a re-render, because the output might change even when the props haven’t.
I’ve debugged components that triggered three API calls instead of one because fetching happened during render, and I’ve seen race conditions where the response to an old request arrived late and overwrote newer data.
Solution
You can move data fetching and analytics calls into useEffect or an event handler, so they don’t run during render, and pass the current time in as a prop.
A lot of bugs come from mixing rendering, which describes what the UI looks like, with effects, which change things outside the component.
A component is pure because of how its render function is written, so you don’t need any extra API. Memoization is an optional optimization that depends on the component being pure. If you wrap a pure component in React.memo, React reuses the last output instead of rendering the component again when its props haven’t changed, and that’s only safe because the same props always produce the same output.
Example
These examples show what goes wrong when a component isn’t pure, what a pure component looks like in each framework, and how memoization depends on purity.
Pure vs Impure
The impure version below checks the current time itself, and the pure version gets the time as a prop, so its output depends only on its inputs.
function ImpureTimestamp({ prefix }) {
const time = new Date().toLocaleTimeString();
return <div>{prefix}: {time}</div>;
} function PureTimestamp({ prefix, time }) {
return <div>{prefix}: {time}</div>;
} Basic Pure Component
A pure component can be a plain function of its props. Each version below only uses its inputs to build the output.
function Greeting({ name, title }) {
return (
<div>
<h1>Hello, {name}!</h1>
{title && <p>{title}</p>}
</div>
);
} <script setup>
defineProps(['name', 'title']);
</script>
<template>
<div>
<h1>Hello, {{ name }}!</h1>
<p v-if="title">{{ title }}</p>
</div>
</template> <script>
let { name, title } = $props();
</script>
<div>
<h1>Hello, {name}!</h1>
{#if title}<p>{title}</p>{/if}
</div> class PureGreeting extends HTMLElement {
static get observedAttributes() { return ['name']; }
attributeChangedCallback(name, oldValue, newValue) {
if (newValue !== oldValue) this.render();
}
// The output only depends on the name attribute
render() {
this.innerHTML = `<h1>Hello, ${this.getAttribute('name')}!</h1>`;
}
}
customElements.define('pure-greeting', PureGreeting); Side Effects in Effects, Not Render
The first version sends a request each time it renders, and each response sets state, which causes another render and another request. In the second version, the effect only runs when userId changes, and its cleanup function sets ignore, so a late response for the previous user can’t overwrite the current user’s data.
function BadProfile({ userId }) {
const [user, setUser] = useState(null);
fetchUser(userId).then(setUser);
return user ? <div>{user.name}</div> : <div>Loading...</div>;
} function GoodProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
let ignore = false;
fetchUser(userId).then(data => {
if (!ignore) setUser(data);
});
return () => { ignore = true; };
}, [userId]);
return user ? <div>{user.name}</div> : <div>Loading...</div>;
} Testing
Pure components are straightforward to test, because you can check that the same props produce the same output. You can’t test ImpureTimestamp this way without faking the clock, because its output depends on when the test runs.
test('same props produce the same output', () => {
const first = render(<PureTimestamp prefix="Updated" time="10:30:00" />);
const second = render(<PureTimestamp prefix="Updated" time="10:30:00" />);
expect(first.container.textContent).toBe('Updated: 10:30:00');
expect(second.container.innerHTML).toBe(first.container.innerHTML);
});
Memoizing a Pure Component
Because a pure component’s output only depends on its props, React.memo can skip the render when the props are the same as last time. React.memo checks whether each prop is the same value or the same object as before, without comparing the contents of objects, so mutating an object won’t trigger a re-render.
const UserDisplay = React.memo(({ user }) => <div>{user.name}</div>);
user.name = 'Bob';
<UserDisplay user={user} /> const updated = { ...user, name: 'Bob' };
<UserDisplay user={updated} /> Functions are compared the same way, so an inline callback prop counts as changed on each render. Memoization and Stable Reference cover how useCallback prevents that, and Immutable Update covers creating new objects instead of mutating them.
Benefits
- Behavior is predictable, because the same props always produce the same output, and you can understand each component without tracing through global state.
- Memoization works, because React.memo can safely skip a re-render when the props haven’t changed.
- Testing is straightforward, because you pass in props and check the output, without mocking global state or worrying about timing.
- Reuse is easier, because a pure component doesn’t depend on outside context that might be missing somewhere else in the app.
- Timing bugs are less likely when side effects run in effects instead of during render, because you control when they run.
- Rendering more than once is safe, because React might render your component more than once before updating the DOM, and with no side effects in render, that doesn’t send duplicate requests or events.
Tradeoffs
- Side effects have to move out of render, so fetching and subscriptions go in useEffect or event handlers instead of running inline.
- Memoization adds work, because React compares the props on each render, and for components whose props change on most renders, React rarely gets to skip one, so the comparison is wasted work.
- React.memo doesn’t compare the contents of objects, so if you change
user.namewithout creating a newuserobject, the component won’t re-render, even though the data changed. - Callbacks need useCallback, because an inline function is a new function on each render, so a memoized child that receives it re-renders anyway, although React Compiler can memoize callbacks for you.
- Imperative code takes extra setup, because focus management and third-party widgets have to go through refs and effects instead of running during render.
- Memoizing everything doesn’t help, because wrapping every component in React.memo “just in case” adds extra comparisons and does nothing for components that weren’t slow to begin with. If you profile first, you’ll know which ones are.
Summary
Pure components produce the same output for the same inputs, with no side effects during render, so frameworks can safely apply optimizations such as memoization, and testing is straightforward. Once the side effects are in useEffect or event handlers, your render function just turns props into UI.