React Hooks Deep Dive
Introduction

Introduction

In this guide, I’ll start things off with a simple TODOs app built (and a bit optimized) with React classes. I’ll explain the core concepts used in that version.

I will then convert the app to use React function components with hooks instead of classes following a simple syntax conversion strategy.

After that, I’ll tell you why simple syntax conversion is not enough and how some optimizations in the class version might stop working and how to fix that.

Before we begin

While anyone on any level can read this guide and start piecing things together, it helps if you have the core fundamental concepts of React in your skill set first. If you’ve never built a React component before please read this first: The Complete Introduction to React

Why A TODOs App?

Because it’s a realistic non-abstract example with a decent set of features that’s not too small or too big. It’s really the new "Hello World" example when it comes to a web UI.

Chances are you’re familiar with the features that are usually presented in it but here’s a recap:

  • Show a list of TODOs

  • Have a checkbox to check a TODO as complete

  • Have a way for the user to delete a TODO and a way to delete all completed TODOs

  • Render a simple form with an input box and a button to add a new TODO to the list

  • Show the count of active TODOs in the UI and as the title of the app

  • Show filtering buttons to make the UI show all TODOs, just the active ones, or just the completed ones

I’ve also added a few constraints to the app:

  • Use an object to manage the list of TODOs (instead of an array for example)

  • Support initial data (to server-render TODOs for example)

  • Optimize component render calls (what React does in memory) and only have React renders what needs to be rendered (when props/state changes)

Please note that the conversion we’re going to do in this guide covers only the common patterns in React like state, props, and mount/update lifecycle methods. It does not cover any "advanced" patterns like context, higher order components, children as a function, etc. There is also no "data fetching" in this conversion.

The class version

Here’s the code and preview for the class version. Give the UI a spin (it’s all interactive) and scan through the code and familiarize yourself with its main parts but don’t worry about the details just yet. I’ll explain the main concepts used here shortly.

Please note that I tried to keep the code simple but realistically close to what you’ll see in actual React apps out there. For example, I used some modern JS features like class fields and arrow functions and avoided manual binding of handlers.