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:

  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 —

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

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
James Broad

James Broad

CTO @ OnCare

More from Medium

Hooks In React

How to create a custom React hook to fetch an API (using TypeScript)?

React Js | JavaScript Frontend Library