Why Redux?
- Good for managing large state.
- Useful for sharing data between containers.
- Predictable state management using the 3 priciples.
Remember, React is a View Layer, which is really good at managing view but doesn't know how to manage state very well.
The 3 Principles
- Single source of truth
- State is read only
- Changes using pure functions
Redux work flow:
This is how JQuery used to work:
This is how Redux work:
Redux was inspired by Flux Pattern:
Before that, we have MVC(Modle View Control):
In a nutshell, Redux is:
But you can still use State:
Let's see how to use Redux: First, use npm install Redux & React-Redux.
npm install redux
npm install react-redux
Second, create an action.js file, which will store all the actions.
export const setSearchField = (text) => ({
type: 'CHANGE_SEARCH_FIELD',
payload: text
})
As you can see, it receives user's input and return an object containing the input as a value of its payload property.
Third, create a constants.js file, which will store all the types of actions.
export const CHANGE_SEARCH_FIELD ='CHANGE_SEARCH_FIELD';
In this way, we can avoid unnoticed missspellings. Because if we use a string and missspelled it, we get no errors, but when we did a variable, we do.
Next, we create a reducers.js file.
const initialState = {
searchField: ''
}
export const searchRobots = (state=intialState, action={}) => {
/*switch is better for adding things later */
switch (action.type) {
case CHANGE_SEARCH_FIELD:
return Object.assign({}, state, {searchField: action.payload});
/* return {...state, searchField: action.payload}; */
default:
return state;
}
}
Then, inside the index.js file, we make some changes:
import {Provider} from 'react-redux';
/*create a store:*/
import {createStore} from 'redux';
/*Then:*/
import {searchRobots} from './reducers';
const store = createStore(searchRobots);
By using the store, we can remove all the states in the App component. Instead, we now can pass store as a prop into the App component.
At the bottom, we add:
ReactDOM.render(
/* Provider can pass down the store to every element inside App*/
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
Using Provider, we can pass the store to all the child tags of App(including App); Without pass to them using:
<App store={store} />