How to use React Hooks
Posted
Updated
Europe’s developer-focused job platform
Let companies apply to you
Developer-focused, salary and tech stack upfront.
Just one profile, no job applications!
Hooks are a new addition in React 16.8 and were first presented at the React Conf in 2018, as a way to manage state and side effects in functional components. Before 2018 function components were more or less stateless, but this has changed since.
React Hooks let you use state and other React features without writing a class. Hooks are also backwards-compatible.
💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.
Hooks solve a wide variety of problems:
Hooks work side-by-side with existing code. A gradual adoption strategy is possible.
React will keep supporting class components for the foreseeable future. Facebook has tens of thousands of components written as classes, and there are absolutely no plans to rewrite them.
Hooks are functions that let you hook into React state and lifecycle features from function components. Hooks don’t work inside classes. You don't need a class.
React provides a few built-in Hooks like useState. You can also create your own Hooks to reuse stateful behavior between different components.
Let's take a brief look at the built-in Hooks useState and useEffect first:
Let's start with the example from the official docs, a simple counter, once build with Class and once with Hooks.
Class
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button
onClick={() =>
this.setState({ count: this.state.count + 1 })
}
>
Click me
</button>
</div>
);
}
}
The state starts as { count: 0 }
, and we increment state.count
when the user clicks a button by calling this.setState()
.
useState Hook
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
The only argument to useState is the initial state. In the example above, it is 0 because our counter starts from zero. Note that unlike this.state, the state here doesn't have to be an object — although it can be if you want. The initial state argument is only used during the first render.
Side effects or simply effects like data fetching, subscriptions or manually changing the DOM from React components can't be performed during rendering.
The Effect Hook, useEffect
, adds the ability to perform side effects from a function component.
It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes,
but unified into a single API.
Hooks can also be combined. Let's say you want to change the document.title in the counter example from above on every change on count.
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
React Hooks are just JavaScript functions, but they impose two additional rules:
To enforce this rules automatically, there is a linter plugin.
Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.
If you want to know more about React, have a look at these React Tutorials.
References (and Big thanks):
Never miss an article.