Redux Best Practices

Rules

  • For more about the deterministic vs non-deterministic, see this Github Issue response.

Reducer composition

Structure and Naming

  • Note: Dan does not endorse ducks because it may confuse beginners into thinking actions map 1:1 to reducers. tweet

Actions

  • DO name each action (constant) as <NOUN>_<VERB> with the present tense
  • Why? For namespacing and sorting your reducers
TODO_ADD
  • DO build your action creators using redux-actions’s createAction()
  • Why? To reduce boilerplate and enforce FSA-compliant actions
createAction( ‘TODO_ADD’ )
  • DO name each action creator as <verb><Noun>
  • Why? As a convention to clearly identify what type of function it is
const addTodo = createAction( ‘TODO_ADD’ )

Selectors

  • DO name each selector as get<Noun>
  • Why? As a convention to clearly identify what type of function it is
const getTodo = (state) => state

Reducers

export default handleActions({

TODO_ADD: (state, action) => ([
...state,
action.payload,
]),

// Other reducers
// ...
//

}, initialState )
  • Why this instead of the documented switch statement? Primarily because it keeps a clean switch-like syntax, while adding block scoping to the cases. This means you can reuse variable of the names in each “case”. With switch, your cases are scoped to the switch, so you are forced to use var or unique names.

Files

  • DO structure your Redux files with the Ducks pattern in a single folder (often called flux/, ducks/, or stores/). Here’s another helpful link.
  • Example reducer:
import { createAction, handleActions } from 'redux-actions';//- Actions
export const addTodo = createAction( 'TODO_ADD' )
//- State
const initialState = []
//- Reducers
export default handleActions({
TODO_ADD: (state, action) => ([
...state,
action.payload,
]),
// Other reducers
// ...
//
}, initialState )//- Selectors
export const getTodos = (state) => state

Types

  • If you are typing your code with Flow or Typescript, be sure to type your redux code as well!
  • Flow: Using Redux with Flow is a nice write-up

Resources

Follow the React Playbook for future updates on this topic!

--

--

--

Full stack web and mobile developer at Chronstruct.com

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kyle Poole

Kyle Poole

Full stack web and mobile developer at Chronstruct.com

More from Medium

React hooks: useState

Building web apps without a central data store

React Hooks — Creating Custom Hooks

React Function Components Lifecycle