React workshop
part 2 - redux
Mateusz Pokora
Michał Gutowski
Kamil Piotrowski
Binar::apps
Redux
Why do we need it?
Redux is a predictable state container for JavaScript apps.
- Unidirectional data flow (top -> down)
- state represented in single tree
Action
payloads of information that send data from your application to your store.
Action
- Add toeat (click button)
- Fetch collection from API (component mount / route enter)
{
type: 'ADD_TODO',
todo: {...}
}
Action creators
Action creators are functions that create actions.
function addTodo(todo) {
return {
type: 'ADD_TODO',
todo: todo
}
}
Reducer
- Listen to actions
- Pure function
- No side effects
- input -> new state
Reducer
// reducer
const reducer = (state = defaultState, action ) => {
switch(action.type) {
case 'ADD_TODO':
return [...state, action.todo];
default:
return state;
}
}
Containers
- connected to store
- listen to state changes
- access to store.dispatch()
- wrapped components
- hold any additional state and logic
Containers
import {connect} from 'react-redux';
import {toggle} from 'actions/toeats';
import ToeatList from 'components/toeat-list';
const mapStateToProps = (state) => {
return {
toeats: state.toeats
};
};
const mapDispatchToProps = (dispatch) => {
return {
onCheckItem: (name) => {
dispatch(toggle(name));
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ToeatList);
Components
- Pure jsx components
- Render based on props only
- No side effects - same set of props renders exactly the same view
Coding time!
ToEat app on redux
- Add toeat
- Complete toeat
- Remove toeat
- Fetch list
React - Redux
By vrael560
React - Redux
- 409