Isolated state. Original image

React State Hooks vs. React Classes in 2 mins

James Broad
2 min readDec 10, 2018

--

The React team seems to have their ear to the ground as they’ve noticed there’s some help needed in managing [simple] state.

Redux and Flux frameworks are great but they’ve got a learning curve, lots of boilerplate and integration cost to get started.

React Hooks have come along and hopes to provide a simple API to:

  1. Easily allow reusue of stateful logic between components
  2. Reduce complexity (E.g. class lifecycle methods or requirement for Flux frameworks)

Let’s jump straight in with a simple stateful toggle component.

Before using classes and setState API:

After using useState hook:

I think that’s a remarkable improvement.

There’s a whole lot more powerful stuff in the hooks API including the Effect Hook and reducers but the React docs do a fabulous job of clearly explaining — https://reactjs.org/docs/hooks-intro.html.

The main gotchas I see at time of writing is the need to use the alpha/next track (React v16.7.0-alpha+) and that it’ll be a reasonable rewrite to move away from stateful classes as you won’t get automatic spread inclusion of object properties when setting state. E.g:

The main benefit I’m seeing is being able to write more (near) stateless functional components and having a highly testable API. Exciting times ahead 🙏.

--

--

James Broad

Exploring strategies and tactics to create a successful tech business