Skip to content

Selectors

The Course
•
20 min study

A selector is a function that picks the part of the state a component needs: (s) => s.minutes. With a selector, useStore returns only that part, and React re-renders the component only when that part changes.

Each component picks its part React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { logSession, sessionStore, setTopic } from "./session.js"; import { useStore } from "./useStore.js"; function Minutes() { const minutes = useStore(sessionStore, (s) => s.minutes); console.log("Minutes rendered"); return <p>{minutes} minutes today</p>; } function Topic() { const topic = useStore(sessionStore, (s) => s.topic); console.log("Topic rendered"); return <p>Studying: {topic}</p>; } export default function App() { return ( <main> <h1>Study Hub</h1> <section className="panel"> <Minutes /> <Topic /> </section> <div className="toolbar"> <button onClick={() => logSession(25)}>Log 25 minutes</button> <button onClick={() => setTopic("Context")}>Switch to Context</button> </div> </main> ); } import { createStore } from "./store.js"; export const sessionStore = createStore({ minutes: 0, sessions: 0, topic: "Reducers" }); export function logSession(minutes) { sessionStore.setState((s) => ({ ...s, minutes: s.minutes + minutes, sessions: s.sessions + 1 })); } export function setTopic(topic) { sessionStore.setState((s) => ({ ...s, topic })); } // A tiny store: state that lives outside React. Any code can read it, change // it, or subscribe to changes, including code that isn't a component. export function createStore(initialState) { let state = initialState; const listeners = new Set(); return { getState: () => state, setState(update) { const next = typeof update === "function" ? update(state) : update; if (Object.is(next, state)) return; state = next; listeners.forEach((listener) => listener()); }, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, }; } import { useSyncExternalStore } from "react"; // Re-renders only when the selected part of the state changes. export function useStore(store, selector = (state) => state) { return useSyncExternalStore(store.subscribe, () => selector(store.getState())); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Watch the console as you press Log 25 minutes, then Switch to Context.

What you'll see

Log 25 minutes logs only Minutes rendered. Switch to Context logs only Topic rendered. Each component re-renders for its own part, and no other.

How it works

JavaScript
export function useStore(store, selector = (state) => state) {
  return useSyncExternalStore(store.subscribe, () => selector(store.getState()));
}

After every store change, React calls the snapshot function again and compares the result with the last one using Object.is. A number or string that didn't change is equal, so the component is skipped.

The pitfall: a new object every time

Change Minutes to select an object:

JavaScript
const { minutes } = useStore(sessionStore, (s) => ({ minutes: s.minutes }));

Run it.

What you'll see

The preview stays blank, and the console says The result of getSnapshot should be cached to avoid an infinite loop. The selector builds a new object on every call, so React never sees two equal snapshots: each check says "changed", which asks for another render, which builds another new object. React stops the loop instead of freezing the page.

Rules for selectors:

  • Return something that's already in the state, or a primitive such as a number, string or boolean.
  • Need several values? Call useStore once for each, or keep a selector that returns an existing object from the state.
  • Need to compute something, such as a filtered list? Select the raw data, then compute during render, with useMemo if it's slow.

Libraries such as Zustand add a shallow comparison option for selecting several fields. Underneath, it's this same rule.

Exercise

Count the sessions

Add a Sessions component that shows 1 sessions logged, using a selector. It must not re-render when you switch topic.

Your working space React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { logSession, sessionStore, setTopic } from "./session.js"; import { useStore } from "./useStore.js"; function Minutes() { const minutes = useStore(sessionStore, (s) => s.minutes); console.log("Minutes rendered"); return <p>{minutes} minutes today</p>; } function Topic() { const topic = useStore(sessionStore, (s) => s.topic); console.log("Topic rendered"); return <p>Studying: {topic}</p>; } export default function App() { return ( <main> <h1>Study Hub</h1> <section className="panel"> <Minutes /> <Topic /> </section> <div className="toolbar"> <button onClick={() => logSession(25)}>Log 25 minutes</button> <button onClick={() => setTopic("Context")}>Switch to Context</button> </div> </main> ); } import { createStore } from "./store.js"; export const sessionStore = createStore({ minutes: 0, sessions: 0, topic: "Reducers" }); export function logSession(minutes) { sessionStore.setState((s) => ({ ...s, minutes: s.minutes + minutes, sessions: s.sessions + 1 })); } export function setTopic(topic) { sessionStore.setState((s) => ({ ...s, topic })); } // A tiny store: state that lives outside React. Any code can read it, change // it, or subscribe to changes, including code that isn't a component. export function createStore(initialState) { let state = initialState; const listeners = new Set(); return { getState: () => state, setState(update) { const next = typeof update === "function" ? update(state) : update; if (Object.is(next, state)) return; state = next; listeners.forEach((listener) => listener()); }, subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }, }; } import { useSyncExternalStore } from "react"; // Re-renders only when the selected part of the state changes. export function useStore(store, selector = (state) => state) { return useSyncExternalStore(store.subscribe, () => selector(store.getState())); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Subscribe to the smallest value the component displays. A change in an unrelated field should leave that snapshot equal.

Hint 2: a first step

Copy Minutes, select s.sessions, and log Sessions rendered to check.

Show one solution
JSX
function Sessions() {
  const sessions = useStore(sessionStore, (s) => s.sessions);
  console.log("Sessions rendered");
  return <p className="muted">{sessions} sessions logged</p>;
}

Add <Sessions /> next to <Minutes />. Switch to Context logs only Topic rendered.

Was this article helpful?

Your response is saved on this device.