Getting started with React Hooks
To try out React Hooks, you will need the alpha build of React (at time of publication)
React Hooks is a new feature that is likely coming in React 16.7. If you have been on Twitter, you have likely seen the amount of buzz surrounding the announcement of React Hooks. A quick look at Google Trends for the past 30 days, reveals that there has been an increased interest in React hooks.
So what are React Hooks and how can you use them in your React code base? We will consider this in this article.
Prerequisites
To get the most out of this tutorial, you need knowledge of JavaScript and the React framework. If you want to play around with React Hooks, you will need the alpha build of React as this feature is still in alpha (as at the time of writing this article).
What are React Hooks?
When you are creating a React application, you usually have to create components. Components are the building block of React applications. React components can be either stateful or stateless.
When you create a component as a class that extends the React.Component
class, you have access to state and React lifecycle methods: componentDidUpdate
, componentDidMount
, and the others.
This is a typical React component. It has access to state and lifecycle methods:
import React from 'react';
export default class extends React.Component {
state = {
name: 'Neo Ighodaro'
}
componentDidUpdate() {
// [...]
this.setState({
name: 'Neo Not Ighodaro'
})
// [...]
}
}
However, when you create stateless components, you don’t have access to state of lifecycle hooks by default.
import React from 'react'
export default () => {
return (
<div className="island">
<h1>Hi, I'm stateless :(</h1>
</div>
)
}
This is where React Hooks come in. React Hooks allows you to access state and lifecycle hooks in a React function component.
Note: React hooks are still in alpha and should probably not be used in a production environment as the API could still change before it reaches the stable build. You can follow the RFC here. You can also look at the documentation and FAQs here.
What about classes in React?
The React team has stated specifically that they do not intend to replace classes as the Facebook team uses them extensively. Hooks are just another arrow in the quiver of tools available. If anything, Hooks can make it easier to break down complex React components as seen in Dan Abramov’s ReactConf 2018 demo code presentation.
With React Hooks, you can extract complex components and break them down into smaller functions that are a lot more testable.
Some in-built React Hooks
Note: At the time of writing, the hooks feature was still in alpha so some of the API might have changed in the stable version of React.
Now that we have talked about what React Hooks are, let’s see some of the Hooks that come bundled with React and how we can use them in our React applications.
The useState hook
Let’s look at a typical React component example:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
export class DoStuffButton extends React.Component {
constructor(props) {
super(props);
this.state = { buttonText: "Do something" };
this.updateButtonText = this.updateButtonText.bind(this);
}
updateButtonText() {
this.setState({ buttonText: "Loading..." });
window.setTimeout(
() => this.setState({ buttonText: "Do something" }),
2000
);
}
render() {
return (
<button onClick={this.updateButtonText}>{this.state.buttonText}</button>
);
}
}
export class App extends React.Component {
render() {
return (
<div className="App">
<DoStuffButton />
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
In the code above, we created a DoStuffButton
component that changes the text when clicked using the state. Then we use the App
component to render it. Simple stuff. Let’s see though how we can simplify the entire code with React hooks; useState
specifically.
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function DoStuffButton() {
const [buttonText, setButtonText] = useState("Do something");
function updateButtonText() {
setButtonText("Loading...");
window.setTimeout(() => setButtonText("Do something"), 2000);
}
return <button onClick={updateButtonText}>{buttonText}</button>;
}
function App() {
return (
<div className="App">
<DoStuffButton />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
While the example is not very practical, it does show how you can use the useState
hook in a React function component.
The useState
function returns an array with two elements. The first item being the current state value and the second being a function used to update the state. Logging the function to the console, we see this:
The useEffect hook
You can read more about the useState
hook in the documentation here. However, let’s see how useState
can be used in code. We will use the same code as we used in the useState
example with the slight addition of the componentDidMount
lifecycle method:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
export class DoStuffButton extends React.Component {
constructor(props) {
super(props);
this.state = { buttonText: "Do something" };
this.updateButtonText = this.updateButtonText.bind(this);
}
// Added this...
componentDidMount() {
this.setState({ buttonText: 'Set this instead'})
}
updateButtonText() {
this.setState({ buttonText: "Loading..." });
window.setTimeout(
() => this.setState({ buttonText: "Do something" }),
2000
);
}
render() {
return (
<button onClick={this.updateButtonText}>{this.state.buttonText}</button>
);
}
}
export class App extends React.Component {
render() {
return (
<div className="App">
<DoStuffButton />
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Above, we added the componentDidMount
lifecycle method to the DoStuffButton
component. This method, as you probably know, will be fired when the component is mounted. So how can React hooks provide us this functionality in a React function component? The useEffect
hook. Let’s see this in action:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function DoStuffButton() {
const [buttonText, setButtonText] = useState("Do something");
useEffect(() => setButtonText('Set this instead'))
function updateButtonText() {
setButtonText("Loading...");
window.setTimeout(() => setButtonText("Do something"), 2000);
}
return <button onClick={updateButtonText}>{buttonText}</button>;
}
function App() {
return (
<div className="App">
<DoStuffButton />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
As seen in the example above, we have implemented the useEffect
hook and it is running when the DoStuffButton
component is mounted.
As said in the docs, “you can think of useEffect
Hook as componentDidMount
, componentDidUpdate
, and componentWillUnmount
combined.”
Rules of React Hooks
As with most things in life, there are some rules to consider when using hooks in your React application. The rules are as follows:
- Call Hooks exclusively at the top level of your function. Don’t put them in loops, conditionals, or nested functions.
By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple
useState
anduseEffect
calls. - Rules of Hooks
- Only call Hooks from function components or custom Hooks. Don’t call them from outside a component.
By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code. - Rules of Hooks
- When writing custom Hooks, use the
use
keyword as a prefix to the name of the hook. This makes it easy to follow convention and makes it easy to spot Hooks when looking at the code.
As a side note, there is an ESLint plugin that enforces these rules. To try it, you can run the following command in your terminal inside the project directory:
$ npm install eslint-plugin-react-hooks@next
// Your ESLint configuration
{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
"react-hooks/rules-of-hooks": "error"
}
}
The plugin will be added to the Create React App and other similar toolkits by default in the future.
Creating custom React Hooks
One more exciting thing about Hooks is custom Hooks. You can create custom Hooks that can be used all around your application. This will reduce duplicated code by a lot when used properly. Custom functions are regular JavaScript functions that have a name prefixed with the use
keyword and have access to React Hooks.
For instance, we can have a custom hook defined like this:
// File: FriendStatus.js
import { useState } from "react";
export function useFriendStatus({ initialState }) {
const [friends, setFriends] = useState(initialState);
const setOnlineStatus = (id, friend, online) => {
if (friend.id === id) friend.online = !!online;
return friend;
};
const setFriendOnline = id => {
setFriends(friends.map(friend => setOnlineStatus(id, friend, true)));
};
const setFriendOffline = id => {
setFriends(friends.map(friend => setOnlineStatus(id, friend, false)));
};
return [friends, { setFriendOnline, setFriendOffline }];
}
// File: index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { useFriendStatus } from "./FriendStatus";
import "./styles.css";
function FriendListItem() {
const [friends, { setFriendOnline, setFriendOffline }] = useFriendStatus({
initialState: [
{ id: 1, name: "Phoebe", online: false },
{ id: 2, name: "Rachel", online: false },
{ id: 3, name: "Ross", online: false }
]
});
return (
<>
{friends.map(friend => (
<li style={{ color: friend.online ? "green" : "grey" }} key={friend.id}>
{friend.name}
<button onClick={() => setFriendOnline(friend.id)}>Set Online</button>
<button onClick={() => setFriendOffline(friend.id)}>
Set Offline
</button>
</li>
))}
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<FriendListItem />, rootElement);
Above we have a simple example of how custom hooks can be used in an application. In the FriendStatus.js
we defined the custom hook and in the index.js
file, we used the custom hooks and the return value to make up the user interface.
Conclusion
In this tutorial, we have learned how to use the new React Hooks feature and how it can improve the readability and testability of complex React components. The introduction of React Hooks should not be seen as a reason to stop using classes but as a tool in your bag to make even better apps.
The source code to the code snippets in this tutorial is available on GitHub.
11 December 2018
by Neo Ighodaro