Skip to content

Build a tiny state store

Deep diveBuild alongTypeScript + ReactYou need: basic React
What you’ll build: A store in about 60 lines of TypeScript, with a React hook that re-renders only the components whose slice changed. Seven steps, each proved by a test.get getState()set setState(partial or fn)sub subscribe(listener)sel select(selector, listener)hook useStore(store, selector)
Step 1 of 7

Set up TypeScript, React and Vitest

Make a folder and write package.json and tsconfig.json, then install. React is the only runtime dependency; the rest are for types and tests.

Vitest runs .ts and .tsx test files directly, so there is no build step. jsdom gives the React tests a fake page to render into.

WHY

Every later step is proved by a test, not by clicking around. A store is plain logic, so tests are the quickest way to see it work.

This step runs:
terminal
$ mkdir tiny-store && cd tiny-store
$ npm install
package.jsonnew+22−0
Added: {
Added: "name": "tiny-store",
Added: "private": true,
Added: "type": "module",
Added: "scripts": {
Added: "test": "vitest run",
Added: "typecheck": "tsc --noEmit"
Added: },
Added: "dependencies": {
Added: "react": "^19.3.1",
Added: "react-dom": "^19.3.1"
Added: },
Added: "devDependencies": {
Added: "@testing-library/dom": "^10.4.2",
Added: "@testing-library/react": "^16.3.3",
Added: "@types/react": "^19.3.0",
Added: "@types/react-dom": "^19.3.0",
Added: "jsdom": "^30.1.3",
Added: "typescript": "^7.0.2",
Added: "vitest": "^5.0.5"
Added: }
Added: }
tsconfig.jsonnew+12−0
Added: {
Added: "compilerOptions": {
Added: "target": "ES2022",
Added: "module": "ESNext",
Added: "moduleResolution": "bundler",
Added: "jsx": "react-jsx",
Added: "strict": true,
Added: "noEmit": true,
Added: "skipLibCheck": true
Added: },
Added: "include": ["src"]
Added: }

Where to go next

Was this tutorial useful?Your vote tells us what to improve next.
Did a step not work, or something unclear?