DEV Community

Francis Vila
Francis Vila

Posted on

Suggestion for new syntax of React reducers + context

The suggestion is this codesandbox.

I was impressed by the example suggested in Scaling Up with Reducer and Context. I spent some time understanding it, and had an idea that the advantages of this technique would justify offering a simpler way of achieving it. Seeing that the React team spectacularly simplified the syntax of function components as compared to the Component class, I hope this is in the spirit of what they are striving to achieve.

The example presented here is forked and edited from the example presented in Scaling Up with Reducer and Context. The syntax suggested here would, if implemented, produce the same effect.

Obviously, the code presented here does not currently function correctly.

The suggestion involves:

  • one new hook, named useContextReducer in the example. It combines the effect of useReducer and useContext.
  • a function to retrieve the state from the parent component, named fetchContextReducer in the example.

I see several advantages to this approach:

  • less code: the file TaskContext.js from the previous example becomes redundant.
  • code is closer to where it is used: namely in the handlers of the components that trigger them, rather than abstracted via dispatchers, type, etc.
  • syntax is similar to that of useState, making it more familiar for entry-level React developers

Top comments (0)