12/30/2019: Converting the new React Blog From ES6 Classes to Hook-using Functional Components

React 16

Introduction

This entry is a discussion of what I experienced when attempting to convert my React blog from ES6 classes to hook-using functional components.

Static HTML Components

I started by converting the components that simply rendered HTML, just to get the React code to work. For example, the Masthead component:

From ES6: To Functional:

class Masthead extends React.Component 
{
  constructor(props) 
  {
    super(props);
  }
  render()
  {
    return(
      ...HTML markup...
    );
  }
}
        

  const Masthead = () =>
{ return( ...HTML markup... ); }

This was pretty straightforward. No errors were encountered.

Dynamic Components

The next part was converting the components that support the context API mechanism.

I noticed in my research that the Provider in most of the use cases that I looked at was not a functional component with hooks but an ES6 class. I tried to leave the Provider class as is and convert the consumers to functional components, using the useContext hook, and at first got the 'useContext is not defined' error. When I added the React reference to the useContext calls, that error went away, but I could not get the code to work.

Further research will be necessary. The useContext() hook is so new that not a lot of use case examples are available at the moment.