The useEffect React Hook

Nausheen Akhter
3 min readAug 26, 2022

--

I successfully implemented the useEffect hook and would like to share some concepts and steps to review.

Create a functional component

First, since I’m working with hooks, I don’t need class components. I created a functional component and worked inside it. I created a counter that counts the number to seconds a user (me) spends on a site.

Quick tip: Install the ES7 React extension (below) so you can use snippets to speed up your coding.

The component is called Seconds and all of the code below autofills using the snippet “rafce.”

I imported the useState and useEffect hooks from the React library like this:

I set up the state using the useState() hook. I rendered a statement including the counter variable.

The useEffect hook replaces the componentDidMount() method used in class components and performs side effects like fetching data, directly updating the DOM, and timers. This hook runs when the component is first rendered. I Additionally, I added an empty array as a second argument. That indicates that this hook should only run once — at the first render. There is a callback function within it that runs at a set interval and therefore has a second parameter.

In the next step, I created a timer using a set Interval function inside the useEffect hook. The setInterval function increments up by one, every 1000 milliseconds (1 second).

This as is will continue to render 1 in the counter because it runs just once when the component first renders. The variable needs to be updated and can be done so with a function inside the setCounter function. I returned the updated version of the state variable within the anonymous arrow function within setCounter().

Next, to make sure that the timer is cleared when I close the window to avoid multiple timers running each time I run this app, I added a clearInterval() function to the hook.

I called the component in my App.js file and ran npm start. Still getting the hang of things but it makes sense so far. Happy coding!

Here’s my repo for this practice.

--

--

No responses yet