Sub topic 1
When You Need Global State, and When You Don't
Prerequisites
Assume you know React function components, useState, useEffect, ES modules, and basic immutable updates. This chapter uses Redux Toolkit (RTK), the recommended way to write Redux logic.
Choose the Right Kind of State
Global state is state that many unrelated parts of an application need to read or update. Examples include the signed-in user, a shopping cart, or shared UI preferences.
Keep state local when only one component, or one small component tree, needs it. A form field, an open menu, or a modal's visibility usually belongs in useState.
Server state is data owned by a server, such as a list of products. RTK Query is usually a better fit for fetching and caching that data than manually storing request status and responses in ordinary slices.
Use Redux when shared client state has complicated updates, many consumers, or transitions that benefit from a recorded history.
The Redux Model: Store, Actions, Reducers, and One-Way Data Flow
A Redux store is the central object containing application state. An action is a plain object describing something that happened. A reducer is a function that calculates the next state from the current state and an action.
The data flow is one-way:
A component dispatches an action. The reducer handles it and produces updated state. Subscribed components read the new state and render again.
Writing a Slice with `createSlice`
A slice groups one feature's state, reducers, and generated action creators. createSlice creates both the reducer and action creators from one definition.
import { createSlice } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
incremented(state) {
state.value += 1
},
amountAdded(state, action) {
state.value += action.payload
},
},
})
export const { incremented, amountAdded } = counterSlice.actions
export default counterSlice.reducerHow Immer Makes Updates Safe
Redux state must be updated immutably. You must not modify the existing state object directly because Redux and React rely on changed references to detect updates.
RTK uses Immer inside createSlice reducers. Immer gives the reducer a temporary draft. You can write mutation-looking code against that draft. Immer records the changes and creates a new immutable state tree.
The state.value += 1 line therefore remains safe. This convenience applies inside RTK-powered reducers, not to arbitrary Redux state or component state.
Exercise
Should a component's temporary input text usually go in Redux?
Show answer
No. Keep it local unless other distant parts of the application must read or update it.