TL;DR

by François Vaux

How I ditched Redux

Update March 2020: Use useReducer!

Redux is probably the most used state management library for React. However, even its own creator has trouble using it, probably because it is one massive piece of bloat and boilerplate.

I used to solve that problem using elfi, a dead simple state management library that I wrote a few years ago. Elfi is a 50 LOC lib that does not carry any difficult to grasp concepts like reducers, thunks or whatever, but instead only relies on functions.

But given the recent additions to React, even elfi is useless now. Using React Contexts, I simply implement state management in my top level component and pass the state management functions through the context:

// AppContext.js
export const AppContext = React.createContext()

// App.js
function App() {
  // The global application state. We use an object here but an
  // immutable value is also a pretty solid choice
  const [state, setState] = useState({ counter: 0 })

  // The dispatch function updates our state by applying a given
  // function on the previous state
  const dispatch = (fn, ...args) => setState(fn(state, ...args))

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      <Button />
    </AppContext.Provider>
  )
}

// Button.js
function Button() {
  const { state, dispatch } = useContext(AppContext)

  return <button onClick={() => dispatch(increment)}>{state.counter}</button>
}

function increment(state) {
  return { ...state, counter: state.counter + 1 }
}

Try it out on CodePen