React Hooks: UseReducer Generics Params In Typescript
The new React Hooks introduces a lot of functions to encourage the creation of function components.
One of those functions is the useReducer.
function useReducer<R extends Reducer<any, any>>(
reducer: R,
initialState: ReducerState<R>,
): [ReducerState<R>, Dispatch<ReducerAction<R>>];
Out of the box, the editor can infer the type of the state when you pass the reduce function. However, when I’ve took the state declaration and put it in an external file, suddenly the editor can no longer infer the type, and my state was of type any.
The solution is simple, you can’t just pass the state and the action to the useReducer generic types, you need to pass a React.Reducer.
const [state, dispatch] = React.useReducer<
React.Reducer<IComponentState, IAction>
>(reduceFunction, initialState); Continue reading
Next article
Hexagonal Architecture: Why Your Domain Logic Shouldn't Know About Your Database
Related Content
Stock Weather AI
A compact AI toolkit that collects market data and news, runs lightweight evaluations, and produces per-ticker weather-style reports for stock analysis experiments.
Codexity Part 1: Architecture of an Answer Engine
The first chapter in a series on building a Perplexity-style answer engine from scratch in Python. We lay out the full architecture, set up the project skeleton, and understand every component before writing a single line of business logic.
Codexity Part 2: Query Rewriting with LLMs
A user types a vague question. The query rewriter transforms it into targeted search queries using a local LLM. We cover intent classification, query decomposition, and prompt engineering that actually works with small models.