Better Programming

Advice for programmers.

Follow publication

Member-only story

Understanding the Closure Trap of React Hooks

Shuai Li
Better Programming
Published in
6 min readJun 25, 2022

--

Now when we develop React projects, we generally use Hooks.

But in the development process, we often encounter some problems. The most classic problem is the closure trap of React Hooks.

Some friends may have encountered similar problems, but they may not understand this problem from the underlying principles of React. Here let’s discuss this topic together.

The Problem

This is a simple React app:

We use useState to create a count state, and continually increase the value of count in the first useEffect, then print the latest value of count in another useEffect at the same time.

How do you think the console output will be?

Here is the result:

--

--

Shuai Li
Shuai Li

Written by Shuai Li

An enthusiastic game player of Earth Online.