Made to simplify the Components callback chain (in React)! Centralize functions and callbacks, all in one place. Redux.
Functions that comunicate directly with the client. Receives client | user information and send it to the Reducer. Basically a callback function.
Store is where all the application's info is stored. It is directly connected to the reducers and the application itself.
Reducers use actions to manipulate itself and the store information.
npm install redux react-redux
// Optional for Redux Dev Tools Integration
npm install --save redux-devtools-extension
/* store/index.js */
import { createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from '../reducer';
const store = createStore(rootReducer, composeWithDevTools());
export default store;
/* reducer/index.js */
import { combineReducers } from 'redux';
import reducerSample1from './reducerSample1';
import reducerSample2 from './reducerSample2';
const rootReducer = combineReducers({ reducerSample1, reducerSample2 });
export default rootReducer;
/* reducer/reducerSample1.js */
import { ACTION_ONE, ACTION_TWO } from '../action';
const INITIAL_STATE = {
****prop1: true,
prop2: false,
};
const reducerSample1 = (state = INITIAL_STATE, action) => {
switch(action.type):
case ACTION_ONE:
return { ...state, prop1: !prop1 }
case ACTION_TWO:
return { ...state, prop2: !prop2 }
default:
return state;
}
export default reducerSample1;
/* action/index.js */
export const ACTION_ONE = 'ACTION_ONE';
export const ACTION_TWO = 'ACTION_ONE';
// actionCreator
export const actionOne = (param1, ...paramX) => {
type: ACTION_ONE,
param1,
paramX,
};
...otherActions
/* index.js */
import ReactDOM from 'react-dom';
import store from './store';
ReactDOM.render(
<Provider store={ store }>
<App />
<Provider />,
document.getElementById('root');
);
import { connect } from 'react-redux';
import { actionName, otherAction } from '../action';
class App extends Component {
render(){
const { prop1, propX } = this.props;
const { actionOne, actionTwo } = this.props;
return (
<div>
<span>Hello World!</span>
</div>
);
}
}
// State from Reducer will be stored in this.props. This can be retrieved from store.getStore() as well
const mapStateToProps = ({ reducer: { prop1, ...propX } }) => ({ prop1, propX });
// Actions that will be used within the Component
const mapDispatchToProps = (dispatch) => ({
actionOne: (params) => dispatch(actionOne(params)),
actionTwo: (params) => dispatch(actionTwo(params)),
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
// export default connect(null, null)(App) - If the component does not use state or dispat