Using the Effect Hook (Testing)

Published on January 3rd 2023

Post Image

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

The Effect Hook lets you perform side effects in function components:

1import React, { useState, useEffect } from 'react';
3function Example() {
4  const [count, setCount] = useState(0);
6  // Similar to componentDidMount and componentDidUpdate:
7  useEffect(() => {
8    // Update the document title using the browser API
9    document.title = `You clicked ${count} times`;
10  });
12  return (
13    <div>
14      <p>You clicked {count} times</p>
15      <button onClick={() => setCount(count + 1)}>
16        Click me
17      </button>
18    </div>
19  );

This snippet is based on the counter example from the previous page, but we added a new feature to it: we set the document title to a custom message including the number of clicks.

Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. Whether or not you’re used to calling these operations “side effects” (or just “effects”), you’ve likely performed them in your components before.

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.