reactjs / react.dev

The React documentation website
https://react.dev/
Creative Commons Attribution 4.0 International
11k stars 7.51k forks source link

React components should be pure, not "idempotent" #7063

Open StevenBrons opened 2 months ago

StevenBrons commented 2 months ago

Summary

A blogpost in the React docs confuses idempotence with purity. Even though this might seem a small typo, it is one of essential importance in that blogpost.

Page

https://react.dev/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024

Details

Idempotence is a property of a function that it returns the same result if you apply the function twice to itself, for example, the absolute value function abs is idempotent, since, abs(abs(x)) = x. In general terms f : X --> X is idempotent iff f ∘ f = f.

This is confused with a pure function. This is a function that, given the same input, returns the same output. It is side-effect free or written in a "functional" style.

Even if this might seem like a minor mistake; it is one of the essential properties that the compiler should check for and to that extent, especially newer developers should not be confused.

StevenBrons commented 2 months ago

After some Google searching, I found a few other occurrences:

eps1lon commented 2 months ago

That's the definition that's used in mathematics. In computer science, the term is somewhat ambigious. E.g. we can find the definition you used (https://foldoc.org/idempotent) but also definitions that just mean "same result if called multiple times" (https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.2). Wikipedia uses the latter definition ("same result if called multiple times"): https://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning

React Hooks and Components must be pure and idempotent ("same result if called multiple times"): https://react.dev/reference/rules/components-and-hooks-must-be-pure#why-does-purity-matter