UNDERSTANDING REDUX Ilya Gelman
UNDERSTANDING REDUX
Ilya Gelman
Ilya Gelman
- Organizer of AngularJS-IL & ReactJS-Israel - Passionate about design and UX
Consultant @ 500Tech
WHAT’S WRONG?
User Interface
User Interface
Controller
User Interface
Controller
Model Model
User Interface
Controller
Model Model Model
User Interface
Controller
Model Model Model
Model
User Interface
Controller
Model Model Model Model
Model
User Interface
Controller
Model
Library
Model Model Model
Model Model
User Interface
Controller
Model
LibraryLibrary
Model Model Model
Model Model Model Model
MVVC
NEW MINDSET
User Interface
User Interface
Dispatcher
User Interface
DispatcherStores
UNI-DIRECTIONAL DATA FLOW
StoresStores
UI IS RENDERED
UI IS RENDEREDSOMETHING HAPPENED
UI IS RENDEREDSOMETHING HAPPENEDSTATE CHANGEDUI IS RENDEREDSOMETHING HAPPENEDSTATE CHANGEDUI IS RENDEREDSOMETHING HAPPENEDSTATE CHANGEDUI RENDERED
FLUX
KEEP IT SIMPLE
Application state is…
ONE SINGLE PLAIN JAVASCRIPTOBJECT
Application state is…
READ-ONLY
PURE* FUNCTION
Current State
Action
New State
* No side-effects
How to change the state
PURE* FUNCTION
Current State
Action
New State
Reducer
PURE* FUNCTION
Current State
Action
New State
const newState = reducer(previousState, action);
{ type: 'ACTION_TYPE', /*...*/ }
import { createStore } from 'redux'; const store = createStore(reducer, initialState);
Responsible for creating a new state every time
The first state we pass to the reducer
Store
getState() dispatch()
subscribe()
Store
function createStore(reducer, initialState) { let state = initialState; return { dispatch(action) { state = reducer(state, action); }, getState() { return state; } }}
Basic Redux
REDUX ♥ VANILLA JS
REDUX
ONE MORE THING…
npm install --save react-redux
1. Put the in context
import { render } from 'react-dom'; import { Provider } from 'react-redux';
render ( <Provider store={ store }> <Root /> </Provider>, document.getElementById('app') );
Store
2. Connect components to store
import { connect } from 'react-redux'; const ImageList = ({ images }) => ( <ul> { images.map((url, index) => ( <li key={ index }>{ url }</li>) ) } </ul>); const mapStateToProps = (state) => ({ images: state.images });export default connect(mapStateToProps)(ImageList);
connect(mapStateToProps,mapDispatchToProps,…
)
Maps part of the stateto component’s props
Maps dispatch functionsto component’s props
REDUX ♥ REACT
REDUX ♥ ANGULAR
REDUX ♥ JQUERY
REDUX ♥ BACKBONE
♥ REDUX
QUESTIONS?
Read our blog:http://blog.500tech.com
Ilya [email protected]