A Useful Flow to Using Redux
Tags: redux, react
Published: 2021-02-20 01:36:29

### Assumptions:
* you've installed Redux and have the `store.js` file setup
* you want a suggestion as to a ‘logical’ flow for when to write `actions`, `reducers`, `component` integration 

* Note: You don’t need to do any of these steps in order but you do need to do each step. Try this method and make up your own method as you go forward.* 


### Step 1 - Create Stateless Components and the GUI
Start with hard-coded data for the time being. 

I’ve found making components this way forces me to think more about their relationships, what the state looks like, and what components could get reused. 

 


### Step 2 - Add Boilerplate 
In the component(s) needing state or props, add the redux boiler plate code and don't worry if they're empty now:

```javascript
// SomeCoolComponent.js file 
import {connect} from 'react-redux'   // every component using mapState or mapDispatch needs this

const SomeCoolComponent = ( { destructuredPropsHere} ) = {
	

    // component code…...

  }

// add the 3 boiler plate lines below at end of file 
const mapStateToProps = state => ({    } )
const mapDispatchToProps = dispatch => ( {   })

export default connect(mapStateToProps, mapDispatchToProps)(TheParentComponentNameHere);
```

### Step 3 - Create a Redux Folder Structure

* Add `./src/redux/` folder to group your `store.js`, `reducers.js`,  and `actions.js` together. This makes it easier to find items and keep focused.

* If you have a lot of `actions` or `reducers`, create a sub-folder and divide the `actions` and `reducers` into related files. For example, `fetchActions.js`, `addToCartActions.js`, or a `loginReducer.js`.  


### Step 4 - Create Your Action(s) and Actions Creator(s)
For example:

```javascript
// actions
export const ISCOMPLETED_TODO = "ISCOMPLETED_TODO"  
export const ADDSINGLEITEM = "ADD_SINGLE_ITEM_TO_STATE"

// action creators
export const setSingleItem = (item) => ({
  type: ADDSINGLEITEM,
  payload: item
})

export const markToDoAsComplete = (text) => ({      
  type: ISCOMPLETED_TODO,   
  payload: {text}
})
```
While very optional, action creators let you easily reuse the object they create. If it seems redundant, it is, on a small scale; but in a larger code base, just type in the action creator name and you get the object.   

### Step 5 - Create or Update  Reducer(s) with  Action(s) 
* Import your ‘actions’ if you are using them (‘actions’ differ from ‘action creators’ )
* Create your a `switch` statement or update a `switch` with a new `case` statement  
* Every `case` needs a `return` with the new state
*Remember to include a `default: return state` for your `switch`

For example:
```javascript 
import {
  CREATE_TODO,
  REMOVE_TODO,
  ISCOMPLETED_TODO,
} from "./actions";

export const toDos = (state = [], action) => {
  const { 
    type, 
    payload, 
  } = action;

  switch (type) {
    // other cases removed for space
    
    case ISCOMPLETED_TODO: {
      const { text } = payload

      return state.map(toDo => {
        if (toDo.text === text) {
          return {...toDo, isCompleted: true}
        }

        return toDo
      })
    }
           
    default:
      return state;
  }
};
```

### Step 5 - Back in Your Component - Import & Props 
* Import the appropriate `action creator(s)`
* Add the appropriate `props` as destructured arguments
* Add the `state` data into `mapStateToProps` in object form
* Add the `action creator` to `mapDispatchToProps` in object shorthand form <-recommended method by Redux
* Add the `state` and the `callback` function into the appropriate spot. 

```javascript
// ToDoList.js for a to do tracking app
// other imports omitted for clarity 
import { connect } from 'react-redux'
import {
  removeToDo,
  markToDoAsComplete,
} from './redux/actions' // action creators, used in mapDispatch

const ToDoList = ({
  toDos = [], 	
  onRemovePressed, 
  markComplete
}) => {

  return (
    <div className="list-wrapper">
    // ...some code here 

      {toDos.map((toDo, i) => {
        return (
        <ToDoListItem 
          toDo={toDo}
          key={i}
          onRemovePressed={ onRemovePressed }  	// callback function
          markComplete={ markComplete } 		// callback function	
        />
        )}
      )}
    </div>
  );
}


const mapStateToProps = state => ({
  toDos: state.toDos,
})

const mapDispatchToProps = dispatch => (
  {
    onRemovePressed: text => dispatch(removeToDo(text)),
    markComplete: text => dispatch(markToDoAsComplete(text))
  }
)

export default connect(mapStateToProps, mapDispatchToProps)(ToDoList);

```



### Now Finished
At this point, you should have everything correctly wired for your casual react app. While a few tutorials (see the to-do code above) help, my understanding improved when I used it for my own project app (outdoor adventure rentals).  

Also, if you haven’t installed the React Developer Chrome extension (link below), install it.  It gives a nice visual of your store. 

### Just The Steps
Step 1 - Create Stateless Components
Step 2 - Add Boilerplate
Step 3 - Create a Redux Folder Structure
Step 4 - Create Your Action(s) and Actions Creator(s)
Step 5 - Back in Your Component - Import & Props

### References & Resources 
[A Deeper Redux CheatSheet - Less Flow, More How](https://dev.to/hudsonmc/redux-cheatsheet-4i43)

[Official React-Redux Tutorial](https://react-redux.js.org/introduction/basic-tutorial) 

[React Developer Chrome Extension](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en)