Isolated state. Original image

React State Hooks vs. React Classes in 2 mins

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:

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 —

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 🙏.

CTO @ OnCare