Redux, First Steps - abukhalil-LTUC-ASAC/amman-401d4 GitHub Wiki

Reduction of context management

Redux is just that, similar to context, but on an even higher pedestal. The solution to having many context on different levels, and even on different front end technologies. Now it being a bit more general solution does complicate the setup process, but otherwise the whole solution is truly at oneness of an object.

The Conversion

Moving away from context cough and to our new friend the redux, a new defining folder called store would contain all necessary states. This store, a groceryStore-like entity would start with the definition, usually in index.js within the store folder where createStore is imported from redux. The definition requires a reducer if you had only one, or a combineReducers to combine multiple reducers that represent different types of actions when needed.

A reducer represents the context type of the past, whether it was for a login, or a vote component state manager, each reducer would be contained in its own file and exported into createStore on compile. reducer takes in two arguments, the state and the action. State represents the initial conditions prior to the call, and action is the change needed to happen when the call is made.

On the app level, we need a Provider from react-redux; that is similar to context, and have a store={store} passed as a prop. Now going directly into the component that would use the state, we would first need to connect it from react-redux to the store using export default connect(mapStateToProps, mapDispatchToProps)(yourComponent);. This allows the component on compile to have access to state and dispatch (action) using props, that are otherwise passed from parent, but now exists directly.

The connect arguments:

  • mapStateToProps would include the states that would be used directly, and changed through dispatch
  • mapDispatchToProps would take in the functions imported from specific store reduce and execute them.

The rest is just normal props to render react component from state, along with onclick props.method that you had already defined in mapDispatchToProps.