State management.
Models applications state as a single JS object
npm install --save redux
a plain javascript objec
{
type: "LOGOUT_USER"
}
Decides which state to return based on the current state and the action.
function rootReducer(state={}, action) {
//can switch what state is returned based on action;
return state;
}
a store is one big javascript object that holds the state for the entire application
const store = Redux.createStore(rootReducer);
store.dispatch({
type: "LOGIN_USER"
})
store.getState();
redux accepts a callback through a listen function
const changeCallback = () =>{
console.log("something changed");
store.getState();
}
const unsubscribe = store.listen(changeCallback);
now whenever the state changed the callback will be called.
dispatch(action) reducer(currentstate, action) newState Invoke Listeners (UI Changes)
React-Redux is a library used to integrate react with redux.
exposes a provider component and a connect function.
Handles: Listeners, passing in state to a component.
install --save react-redux
Wrap your top level app in Tags and create a store.
const store = createStore(rootReducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root');
)
connect (getthestate, callanaction)(name of component)
const MapStateToProps = state => ({name: state.name})
export default connect(mapStateToProps, null)(BoldName);
const DelName = ({delName}) => (
<button type="button" onClick={delName}>Delete</button>
)
mapDispatchToProps =(dispatch, ownProps) => (
{
delName: () =>(dispatch(
{
type: "DEL_NAME"
}
))
}
)
export default connect(null, mapDispatchToProps) (DelName);
"Dumb" component or stateless functional component show things in regards to the ui
stateful component that deals with application data
often created using higher order componenets
Each reducer is only responsible with its state;
const rootReducer = combineReducers({
currentUser,
messages,
});
src actions components containers reducers index.js