Skip to the solution
MediumFrontend7 min read

Implement a Memoized Selector That Only Recomputes When Its Specific Inputs Change (Reselect-Style)

1.1k views

The problem

Problem, as an interviewer would state it: "Implement a Reselect-style createSelector(inputSelectors, resultFn) — a derived-state selector that only recomputes when one of its DECLARED input selectors' own output actually changes, ignoring unrelated state changes entirely."

Examples:

Code
const getFilteredItems = createSelector([getItems, getFilter], (items, filter) => items.filter(i => i.includes(filter)));
getFilteredItems(state); // computes
getFilteredItems({ ...state, unrelatedField: 2 }); // returns the SAME cached result, no recompute

Clarifying questions expected:

  • Does the memoization compare the FULL state object, or just the specific input selectors' own outputs?
  • Should the comparison be a shallow reference check (===) or a deep equality check?
  • Does the selector need to support MULTIPLE independent instances, each with their own cache?

Code / implementation expected: Yes — real, direct proof that an unrelated state change does not trigger recomputation (same cached reference returned), while a relevant one does.

  • memoization
  • redux
  • state-management

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a memoized selector returns the same cached reference for an unrelated state change and recomputes for a relevant one

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 83 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Build a Form Validation Utility Supporting Field-Level and Cross-Field Rules

Continue