React Hooks: A Simple Introduction

A simple introduction to React Hooks

Table of Contents

What are React Hooks?

React Hooks are a newly proposed feature that lets you use state and life-cycle methods without writing a class component.

Hooks are currently part of React v16.7.0-alpha (as of November 2018). The React team are openly discussing Hooks as part of an RFC (Request for Comments).

If accepted, Hooks will be part of React v16.7.

React Hooks allow us to take Stateless Functional Components and apply state and lifecycle methods to them. As a result, this makes Class Components useless. However, they can still be used as React Hooks are backward compatible.

Why React Hooks?

There are two types of React components: Class Components and Stateless Functional Components. The differences between the two are:

  • Class components have a state and provide access to lifecycle methods like componentDidMount and componentDidUpdate.
  • Stateless functional components are pure functions that do not have a state or lifecycle methods. They take in props and return HTML.

Lifecycle methods in class components could contain a mix of unrelated logic. For instance, additional setup for that component or making API calls to fetch data.

It is also harder to share logic between class components without using design patterns and implementations like render props and higher-order components.

As a result, class components are harder to understand, more complex, and require more time and effort to maintain. Hence, the need for a simpler implementation.

Installing React Hooks

To use React Hooks, you need to upgrade the version of React and React-DOM to ‘16.7.0-alpha.2’. We’ll do this by using Create React App to spin up a new React app, then specify the new alpha version of React in the package.json file.

Let’s begin by creating a new React project using Create React App. Open your terminal and run the following to create the new project:

npx create-react-app react-hooks
cd react-hooks
npm start

Open up the project in your favorite text editor, and navigate to package.json Find and replace the ‘dependencies’ object with the lines below:

If you’re using Atom, take a look at my best Atom packages for front end developers.

  ...
  
  "dependencies": {
    "react": "^16.7.0-alpha.2",
    "react-dom": "^16.7.0-alpha.2",
    "react-scripts": "2.1.1"
  },
  
  ...

Jump back to your terminal and run npm install to upgrade the version of React and React-DOM.

npm install
npm start

Great! Make sure the project still works, and if all looks good we’ll get into writing our first hook!

Using the State Hook

We’ll begin by creating a very, very simple Stateless Functional Component. Begin by opening up App.js and replacing the entire file with the code below:

import React from 'react';
import './App.css';

const App = () => {
  return (
    <div className="App">
      <h1>Hello, World!</h1>
    </div>
  );
}

export default App;

Twelve lines to create the world’s simplest React component! Save your file and jump over to the running app in your browser. You should see something like this:

Now that we have a simple React component, let’s use React Hooks to add state to it, without converting it to a class component.

import React, { useState } from 'react';
import './App.css';

const App = () => {
  const [name, setName] = useState('World');
  return (
    <div className="App">
      <h1>Hello, {name}!</h1>
      <button onClick={() => setName('James')}>
        Click me to change the name
      </button>
    </div>
  );
}

export default App;

Let’s break down the code above to explain what we’ve added and how it works.

  • Importing the useState hook from React.
  • Creating a new constant that returns a pair of objects: name and setName from useState.
  • Initializing the useState hook with a value of ‘World’.
  • Using the ‘name’ state property by inserting it after ‘Hello’, {name}.
  • Adding a button with an onClick handler that calls the setName function of useState with the value, ‘James’.

Clicking the button changes the name property in the state from ‘World’ to ‘James’. Save your file and try it out!

As always, experiment with the code before moving on so you fully understand what we’ve accomplished.

Using the Effect Hook

If you’ve written React class components before, you should be familiar with lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.

The useEffect Hook is all three of these lifecycle methods combined. 

Open up App.js and import useEffect at the top of the file.

import React, { useState, useEffect } from 'react';

...

Now that we’ve imported the useEffect React Hook, we can use it anywhere in our functional component, like so:

const App = () => {
  const [name, setName] = useState('World');

  useEffect(() => {
    document.title = `Hello, ${name}`;
  });

  return (
    <div className="App">
      <h1>Hello, {name}!</h1>
      <button onClick={() => setName('James')}>
        Click me to change the name
      </button>
    </div>
  );
}

Save the file and open up your running React app. Look at the browser tab, it should say ‘Hello, World’. Click the button and watch it change to ‘Hello, name’.

A browser tab showing a title change

useEffect is run once when the component finishes loading for the first time, and then every time the component state is updated. Because the button click is modifying the state, the component useEffect method runs. 

Wrapping Up

So there you have it, a quick introduction to React Hooks. As always, leave a comment if you liked the post or if you have a question.

Thanks for reading!


We'll only ever send you our latest tutorials each month, nothing more. Not like those idiots at Wayfair who send you fifty-million emails a day about their latest sale, ugh.


Write a response

Your email address will not be published. Required fields are marked *

We will never share your email with anyone else.

Comments

Hersko says:

Great lesson!

Just a heads up but your link to your recommended Atom packages in the article is no good. It takes you to: https://blog.upmostly.com/best-atom-packages-front-end/ which is no good.

The link on bottom works though.

James King says:

Thanks, Hersko! I’ll get that link fixed ASAP.