Reducers are pure functions in redux which are used
to modify the state object of the Application. All Actions are handled in
reducers they will get the payload from the action and modify the state as
defined.
Reducers take the previous state of the app and return a new state based on the action passed to it.
Reducers take the previous state of the app and return a new state based on the action passed to it.
As pure functions, they do not change the data in the object passed to
them or perform any side effect in the application. Given the same object, they
should always produce the same result. Actions performed on the state always
return a new state. Thus, the state is very easy and predictable.
In the previous post, we was a SET_NAME action below is the reducer which handles the SET_NAME action.
const initialState = {
In the previous post, we was a SET_NAME action below is the reducer which handles the SET_NAME action.
const initialState = {
name: '',
greeting: ''
};
export const homeReducer = function (state = initialState, action) {
switch (action.type) {
case "SET_NAME":
return {
...state,
name: action.payload.value
};
case "SET_GREETING":
return {
...state,
greeting: `Welcome
${action.payload.name} !!!`
};
default:
return state;
}
};
The reducer case which handles the SET_NAME action takes the value from the payload and updates it to the name property in the state, the modified state is returned back.
The store object (application’s state) is created using the reducer as follows. createStore() takes an optional 2nd parameter which can be used to initialize the state when the application starts.
import { createStore } from 'redux';
The reducer case which handles the SET_NAME action takes the value from the payload and updates it to the name property in the state, the modified state is returned back.
The store object (application’s state) is created using the reducer as follows. createStore() takes an optional 2nd parameter which can be used to initialize the state when the application starts.
import { createStore } from 'redux';
import { homeReducer } from './homeReducer';
export const store =
createStore(homeReducer);
The store object is injected to the root Component via the Provider component as follows.
<Provider store={store}>
The store object is injected to the root Component via the Provider component as follows.
<Provider store={store}>
<HomeComponent
/>
</Provider>
No comments:
Post a Comment