React Native
Reducer function
Learn to write a reducer function.
What is a reducer function?
A reducer is a pure function that takes the current state and an action and returns the new state. It usually holds a switch statement; each case matches an action type. Example: function reducer(state, action) { switch (action.type) { /* ... */ } }.
A reducer has two core principles. First it must be pure: it produces a new state only from state and action, with no side effects. Second it must not mutate the old state: it always returns a new object or value. These two principles make a reducer predictable and testable. When an unknown action arrives, returning state unchanged in the default branch is a common pattern.
A reducer example
A typical reducer manages a counter. state is a number; action.type can be "increment", "decrement" or "reset". Each matching case computes the new state.
Example: case "increment": return state + 1;. Since state is a number, the new number is returned directly. If state were an object, you would write return { ...state, count: state.count + 1 } to build a new object. A reducer must always return a new value; it must not mutate the current state. The default branch returns state unchanged for unknown actions.
Exercise Write a reducer
Write a reducer function. It takes two parameters: state and action. Use switch (action.type); in the "increment" case return state + 1. In the default branch return state.
Show example solution
function reducer(state, action) {
switch (action.type) {
case "increment":
return state + 1;
default:
return state;
}
}
Test yourself
-
Complete the switch case
switch (action.type) {
case "increment":
return state + 1;
case "____":
return state - 1;
default:
return state;
}
Show answer
switch (action.type) {
case "increment":
return state + 1;
case "decrement":
return state - 1;
default:
return state;
}
-
What does a reducer return?
function reducer(state, action) {
/* ... */
}
- Yeni state
- Mutates the old state
- Yeni action
- Nothing
Show answer
Yeni state — A reducer returns new state.
-
Match each piece to its role
- reducer
- Computes state
- state
- Current state
- action
- Event description
- switch
- Branch picker
Next lesson: Action dispatch