How can you change the state in Redux?
sobes.tech AI
Answer from AI
The state in Redux can only be changed through dispatching actions. Actions are simple JavaScript objects that describe what happened. Reducers are pure functions that take the current state and an action, and return a new state.
The process of changing state:
-
Creating an Action: An action object is defined with a type (the
typefield) and optional data (payload).// Example of an action to change a value { type: 'SET_VALUE', payload: 10 } -
Dispatching an Action: The
dispatchmethod from the Redux store is used to send the action.// Getting the store (in a real app, the store is usually accessible via context or hooks) const store = ...; // Dispatching the action store.dispatch({ type: 'SET_VALUE', payload: 10 }); -
Handling the Action in the Reducer: The reducer receives the current state and the dispatched action. Depending on the
type, the reducer computes and returns a new state. It is important that the reducer is a pure function: it should not mutate the existing state but always return a new state object.// Example reducer function myReducer(state = { value: 0 }, action) { switch (action.type) { case 'SET_VALUE': // Return a new state without mutating the old one return { ...state, value: action.payload }; default: // Return the current state by default return state; } }
Alternative approaches (using Redux Toolkit):
-
Creating actions and reducers with
createSlice: Redux Toolkit significantly simplifies the process by automatically creating action creators and reducers based on defined "slices" of state.// Example with createSlice import { createSlice } from '@reduxjs/toolkit'; const mySlice = createSlice({ name: 'myState', initialState: { value: 0 }, reducers: { setValue: (state, action) => { // Immer allows direct mutation of state, but under the hood, a new object is created state.value = action.payload; } } }); export const { setValue } = mySlice.actions; export default mySlice.reducer; // Dispatching an action created from the slice store.dispatch(setValue(20));
It is important to remember: directly modifying Redux state (e.g., store.getState().value = 10) is strictly prohibited and will lead to unpredictable behavior. Always use dispatch actions.