A companion repo for the blog post "Solving React Re-Renders with a Subscription-Based Provider".
How to move from a standard React Context provider (where every consumer re-renders on any change) to a subscription-based service with field-level filtering.
The commit history walks through each step:
- Baseline — standard Context +
useSettingshook. All 20 consumers re-render on any change. - Subscription service — state lives outside React in a class with
BehaviorSubject. Components subscribe viauseEffect. - Field-level filtering — hook accepts
(category, fields)and only triggers setState when watched fields change. - Stable dependency arrays —
useStableArrayprevents unnecessary re-subscriptions from array literals in deps.
pnpm install
pnpm devOpen http://localhost:5173 and watch the render counts.
src/settings/types.ts— nested settings type definitionsrc/settings/SettingsService.ts— plain class + BehaviorSubject (state outside React)src/settings/useSettings.ts— subscription hook with field-level filteringsrc/settings/useStableArray.ts— dependency array stabilization utilitysrc/components/SettingCard.tsx— displays one field with render countersrc/components/ControlPanel.tsx— buttons to toggle settings