Typically, each component has a state.
class ListItem extends Component {
constructor() {
this.state = {
selected: true
}
}
}This works really well for simple applications, but what if one state change affects another component? Or, what if state changes start to conflict with one another? This is where it helps to keep track of state changes in one centralized location.
In redux, state is a plain object.
{
todos: [
{
id: 1,
text: 'My list item',
completed: false
}
]
}To change the state, you must dispatch an action.
{
type: 'ADD_TODO',
payload: 'My new list item'
}- Must have a type
- Might be defined in a separate file
Actions are processed by a reducer.
Note: Reducer function should always return a new object rather than mutating the existing state.
function reduce(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
{
id: 1,
text: action.payload,
completed: false
}
]
default:
return state;
}
}- Data should be separate from UI state
- State should be as normalized as possible without any nesting
- Every entity should have an ID, like in the database
Actions are processed the the store. The store is a singleton that is shared by every class.
store.dispatch(new AddTodoAction('my todo'));