Redux is a pattern and a library for organizing global state in your application, outside of the React componentry. Redux, itself, does not depends on any UI library. It’s most commonly-used with React. And the idea is that you provide a separation between the code that manages your data and updates it and the parts of your code that say,
- Action – What to do ?
- Reducer – How to do ?
- State – Object holding state of application
State
Imagine your app’s state is described as a plain object. For example, the state of a todo app might look like this:
{
todos: [{
text: 'Eat food',
completed: true
}, {
text: 'Exercise',
completed: false
}],
visibilityFilter: 'SHOW_COMPLETED'
}
Action
Actions are plain Javascript Objects that have a type field. Actions only tell what to do, but they don’t tell how to do.
Enforcing that every change is described as an action lets us have a clear understanding of what’s going on in the app. If something changed, we know why it changed. Actions are like breadcrumbs of what has happened.
{ type: 'ADD_TODO', text: 'Go to swimming pool' }
{ type: 'TOGGLE_TODO', index: 1 }
{ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }
Reducer
Reducers are functions that take the current state and an action as arguments, and return a new state result.
Finally, to tie state and actions together, we write a function called a reducer. It’s just a function that takes state and action as arguments, and returns the next state of the app. It would be hard to write such a function for a big app, so we write smaller functions managing parts of the state
function visibilityFilter(state = 'SHOW_ALL', action) {
if (action.type === 'SET_VISIBILITY_FILTER') {
return action.filter
} else {
return state
}
}
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([{ text: action.text, completed: false }])
case 'TOGGLE_TODO':
return state.map((todo, index) =>
action.index === index
? { text: todo.text, completed: !todo.completed }
: todo
)
default:
return state
}
}
And we write another reducer that manages the complete state of our app by calling those two reducers for the corresponding state keys:
function todoApp(state = {}, action) {
return {
todos: todos(state.todos, action),
visibilityFilter: visibilityFilter(state.visibilityFilter, action)
}
}
Store
The Redux store brings togehter the state, actions and reducers that make up your app.
Please Note: App will only have a single-store.
Please Note: Every Redux store has a single root reducer function.