Theo did a video this week about unintuitive behaviors of React hooks, exploring especially the idea of a hook called usePrevious, to keep the value version of the last re-render, before the current one. A way of doing some logic with the old and new state.
If you want to see ideas of how to implement it, please check the video, in this post the idea is to explore the conceptual aspect of having a hook like usePrevious.
Reactive expressions
As you can see, we don’t have a primitive hook like this in React. Before hooks, in the class-based era, we had a lifecycle method called componentDidUpdate where we got all the previous state and props as parameters, why didn't they keep this behavior with hooks?
It can be a little repetitive if you are reading this series of posts, but we need to talk about the paradigm shift, in this case.
With classes, when some state updates, you don’t have an automatic way of recalculating the derived values. If you are using some specific props and states to calculate some new value, you need to verify by yourself if some of them have changed.
This way, the solution is to have a callback that is called in all updates, and send to the user the previous values. The app code checks the differences and updates the calculated state with the new result. This is the directness of class-based components, you have complete control of the flow of data, and need to manually control the calculations.
Here we come to reactivity expressions.
Instead of having to check and do the change, you write an expression, the calculation formula, sort of. This calculation needs to be executed with the current state version, without access to the previous one.
Imagine a formula:
a = b + c b = 10 c = 20 a = 10 + 20 a = 30
If I use this expression 1 million times, passing b as 10 and c as 20, I will get the same result. This is a pure calculation. React performs the same principle. All calculations of derivations should be pure.
But why it matters?
React work in re-renders. Each cycle generates a description of the UI and based on the differences between the current one and the next one, it commits changes to the DOM. Each render is completely separated from the previous or the next.
UI = fn(state)
So for each different state version, we got a different UI version. This becomes pretty confusing if we add previous values here. Because now it does not just depend on the state, but on the previousState as well. Instead of having one source, one expression and one result, I can have multiple sources, maybe more complex expressions to handle these sources and inconsistent and unpredictable UI as result.
Each render will behave differently based on the previous state. And as some of the possible implementations of usePrevious rely on time ordering in React, this becomes more dangerous.
With concurrent features, React can stop without warning a render, to prioritize other actions. Depending on useEffect and ref can make you keep a stale version of a “previous” render that is even the real previous one. More mess to reason about.
Memoization
Think in an expression like this
a = b + c b = 10 c = 20 a = 10 + 20 a = 30
One part of that has priority and needs to be calculated before, let’s think it with javascript code:
UI = fn(state)
So now we have two separated expressions that can be calculated separately, and are perfectly pure. But if the value of b changes a lot and the calculation for cdResult is expensive, how can we solve it? Memorizing!
a = b + (c - d)
Now cdResult will just be recalculated if c or d changes.
But above in the text I said there is no previous value, but how can a calculation of one render be used in the next one? This doesn't break the purity of calculations?
Actually, no. For example:
const cdResult = c - d; const a = b + cdResult;
Imagine we are in the render number 1. The c has the value of 30 and d has the value of 20, so the result is 10. But as I am memoizing it, React will keep track of the dependencies I added on the array. If some of them change, it recalculates.
const cdResult = React.useMemo(() => c - d, [c, d]); const a = b + cdResult;
But they didn’t change. If I call this expression again, with c as 30 and d as 20, I will get the same 10 as result. Even though I am in the render number 2 and other variables have changed, the dependencies I use in this calculation didn’t change.
I can calculate it again in each render, it’s the default behavior of React, but I can choose to skip an unnecessary recalculation that will return the same value, so I kept it. We kept the purity and we kept the separation between renders
Previous state
But there is a good place to do logic with previous state, user actions. Of course, that in the moment the callback is called, that would be the current state. But if you have some state that needs to change based on some logic, it’s the place.
Of course it can have very specific cases where maybe you need a hook such as usePrevious, but be aware of the inconsistencies it can cause, and try to add guarantees to avoid bugs on the application.
And more importantly, if possible, avoid it.
The above is the detailed content of The problem with usePrevious and similar time oriented hooks. For more information, please follow other related articles on the PHP Chinese website!

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment
