Common Pattern: Reusable Init Functions
What you'll learn: How to extract initialization logic into pure functions that can be tested independently and shared across multiple reducers.
Making Init Functions Reusable
When you extract initialization logic into an init function for useReducer, you're creating a pure function that transforms input into initial state. The beautiful part? These functions can live outside your component entirely, making them:
- Testable in isolation (no React needed)
- Shareable across components
- Composable with other init functions
The Pattern
Instead of defining init inline, extract it as a standalone function:
// Separate file: initFunctions.ts
export function initializeCounter(startValue: number) {
return {
count: startValue,
lastUpdated: Date.now(),
incrementCount: 0
};
}
// Component A
function CounterA() {
const [state, dispatch] = useReducer(
counterReducer,
10,
initializeCounter
);
// ...
}
// Component B (different component, same logic!)
function CounterB() {
const [state, dispatch] = useReducer(
counterReducer,
25,
initializeCounter
);
// ...
}
Why This Matters
Think of init functions like recipe templates. You wouldn't rewrite the recipe every time you bake cookies—you'd use the same recipe with different quantities. Init functions work the same way: one function, many uses.
You can now:
- Unit test
initializeCounter(10)without mounting components - Share the same initialization logic across different parts of your app
- Compose multiple init functions together for complex state
Key Takeaway: Extracting init functions into standalone, pure functions makes them testable, reusable, and shareable—turning initialization logic into modular building blocks rather than component-locked code.