How to handle application wide state
Prevent Prop Drilling
Context must be created using
const YourContext =
createContext<ValueType>(…)
The parameter is the default value of the context.
Provide context in an ancestor component using
Consume within any descendant component using
const value = useContext(YourContext)
Any JavaScript object can be the value of a context.
UserContext.ts
Profile.tsx
App.tsx
Layout.tsx
It depends.
React provides built-in Hooks for flux-based state management without having to use Redux .
Takes a reducer function and an initialState
Returns an array with two values, the current state and a dispatch function
const [state, dispatch] = useReducer(reducer, initialState);
Is called with two parameters
function reducer(state: State, action: Action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error("unknown action type");
}
}
type State = {
count: number;
}
type Action = { type: 'increment' | 'decrement' }
Don't count multiple visits to the same pokemon.
usePokeVisit.ts types
A rough overview of the different solutions available
Provide additional features that useReducer does not:
Permit direct state mutation
Primary focus on state and selectors
Finite state machines and state charts
Prefer simple solutions for state management
How is the state used and what is the source of truth?
Server State: Tanstack Query
Client State: useState/useReducer
Location State: path, search params (e.g. /pokemon?limit=5&offset=5)
Global State: Context, Redux, Zustand, ...
We learned…