It's great for views but
it's bad at state management.
Especially for single page apps.
State mutates over time and you always have to keep in mind the previous state and the next state.
The state of your whole application is stored in an
object tree within a single store.
Store can be easily initialized from a cached copy.
Easier to debug because everything is in one place.
Simpler to save the app state for development.
Only way to change the state is to emit an action,
an object describing what happened.
Views or callbacks don't ever write to the state.
All changes happen in a centralized way
and in strict order.
Pure functions are functions that don't have side effects. Same inputs in always return the same outputs.
To specify how the state tree is transformed by actions, you write pure reducers.
Reducers are just pure functions that take the previous state and an action, and return the new state.
(previousState, action) => newState
Actions are payloads of information that send data
from your application to your store.
const ADD_TODO = 'ADD_TODO'
{
type: ADD_TODO,
text: 'Build my first Redux app'
}
dispatch({
type: ADD_TODO,
text: 'Build my first Redux app'
})
Action creators are functions that create actions.
const ADD_TODO = 'ADD_TODO'
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
dispatch(addTodo(text))
A reducer specifies how the the state changes to actions.
const initialState = {
todos: []
}
function todoAppReducer(state = initialState, action) {
switch (action.type) {
case ADD_TODO:
return Object.assign({}, state, {
todos: [
...state.todos,
{
text: action.text,
completed: false
}
]
})
default:
return state
}
}
Holds application state
Allows access to state via getState()
Allows state to be updated via dispatch(action)
Registers listeners
There is only one store in a redux app.
It may can contain multiple reducers.
store.dispatch(addTodo('Learn about actions'))
All the actions we have talked about are synchronous. Meaning, every time an action was dispatched,
the state was updated immediately.
What if an action requires a call to a database?
What if an action takes a while to complete?
We can't stop the app to wait for these actions to finish.
So what do we do?
There is a library called redux-thunk
that defines a pattern to solve this.
It creates an action that can call other actions.
The action creator is going to return a
function instead of an object.
function addTodo(text) {
return { type: ADD_TODO, text }
}
function fetchTodos() {
return function(dispatch) {
dispatch(requestTodosStart())
return fetch('http://www.todos.com/')
.then(response => response.json())
.then(json =>
dispatch(addTodos(todos))
dispatch(requestTodosSuccess(todos))
)
.catch(error =>
dispatch(requestTodosError(error))
)
}
}