Introduction

Learn how to access the state of the router and perform navigation from inside function components using Hooks.

ESLint and Hooks

If we want to use Hooks and implement them in our applications, we need to follow a few rules that prevent us from running into unexpected errors or behaviors. ESLint and the eslint-plugin-react-hooks package, which has been developed by the React Team itself, helps us to follow these rules and indicate when we might be breaching one. We advocate for the use of ESLint and recommend that you use it if you have not done so already.

To install the plugin, you can execute the following command on the command line:

npm install --save-dev eslint-plugin-react-hooks

Or, using Yarn:

yarn add --dev eslint-plugin-react-hooks

In addition, you need to amend the .eslintrc as shown:

{
  "plugins": [
    // ...
    "react-hooks"
  ],
  "rules": {
    // ...
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn"
  }
}

Note: I’ve got Good news for those of you who are using Create React App! You do not need to do any of the previous steps, because those two specific rules ship with Create React App out of the box.


The rules of Hooks

We talked about the formalities and how to check that we are not violating the predefined rules for Hooks. But what are those rules exactly? Let’s look at them.

Only call Hooks from React functions

Hooks can only be called in React function components, not in class components or anywhere else. This means that a function that uses Hooks always has to be a React component,or it always has a return value (either JSX, Arrays, Strings, or null).

The following is not allowed because it uses a class component:

class MyComponent extends React.Component {
  render() {
    const [value, setValue] = React.useState();
    return (
      <div>
        <div> Value: {value} </div>
        <input type="text" onChange={(e) => setValue(e.target.value)} />
      </div>
    );
  }
}

The compiler will rightfully throw the following error:

Get hands-on with 1200+ tech skills courses.