---
title: "Is React Really UI = f(State)?"
description: "What purity and idempotence mean - reading React more carefully through category theory, algebraic effects, and Applicative structure"
last_updated: "2026-11-15"
canonical_url: "https://wtrclred.vercel.app/en/posts/09"
language: "en"
---

Turn on watercolor background effects. * May affect performance, battery life, and temperature on some devices.

### Table of Contents

- [Introduction](#introduction)
- [The Mathematical Meaning of "Pure"](#the-mathematical-meaning-of-pure)
- [The Original Meaning of "Idempotent"](#the-original-meaning-of-idempotent)
- [Idempotence in Mathematics](#idempotence-in-mathematics)
- [React's "Idempotence" Is Not Mathematical Idempotence](#react-s-idempotence-is-not-mathematical-idempotence)
- [The Rendering Operation Can Be Expressed as Idempotent](#the-rendering-operation-can-be-expressed-as-idempotent)
- [React Fiber and Algebraic Effects](#react-fiber-and-algebraic-effects)
- [What Are Algebraic Effects?](#what-are-algebraic-effects)
- [Function Composition in the Kleisli Category](#function-composition-in-the-kleisli-category)
- [Kleisli Category](#kleisli-category)
- [A React Component Is a Kleisli Morphism](#a-react-component-is-a-kleisli-morphism)
- [Component Composition](#component-composition)
- [Monad Bind and an Applicative Skeleton - What a Component Body Really Is](#monad-bind-and-an-applicative-skeleton---what-a-component-body-really-is)
- [The Rules of Hooks Make an Applicative Skeleton Possible](#the-rules-of-hooks-make-an-applicative-skeleton-possible)
- [use and Suspense - A Concrete Form That Resembles Algebraic Effects](#use-and-suspense---a-concrete-form-that-resembles-algebraic-effects)
- [The Mistake of Client-Server "Isomorphism"](#the-mistake-of-client-server-isomorphism)
- [Isomorphism in Category Theory](#isomorphism-in-category-theory)
- [Server Rendering and Client Rendering Are Not Isomorphic](#server-rendering-and-client-rendering-are-not-isomorphic)
- [A More Accurate Description: Different Effect Handlers](#a-more-accurate-description-different-effect-handlers)
- [Conclusion: Rewriting UI = f(State)](#conclusion-rewriting-ui-f-state)
- [Problems with the Naive Equation](#problems-with-the-naive-equation)
- [A More Accurate Description](#a-more-accurate-description)

> Note : I am not a mathematics specialist. This essay is an attempt to use the vocabulary of category theory, algebraic effects, and Applicative structure to understand React, so please read it as a proposed reading rather than a rigorous theorem. If you notice a mathematical mistake, I would be happy to be corrected.

# Introduction

 "UI = f(State)" - this is one of the most widely circulated equations in discussions about React.
At first glance, the equation looks simple and seems to capture the essence of React: if the state is determined, the UI is determined.

 However, when we read this equation carefully in mathematical terms, several points need clarification.

- What is this f ? Is it a "function" in the mathematical sense?

- If it is a function, in which category is it a morphism?

- Are React's notions of "pure" and "idempotent" the same as the mathematical ones?

 In this essay, I will use the vocabulary of category theory, algebraic effects, and Applicative structure to try to read React Components more precisely.

# The Mathematical Meaning of "Pure"

 Let us clarify the mathematical meaning of the word "pure," which is often used in React documentation and discussions.

 In mathematics, a pure function is a mapping with referential transparency.
In the language of category theory, it corresponds to a morphism in the category of sets, Set :

 f : A → B f: A \to B f : A → B
 This morphism `f` satisfies the following:

- It always returns the same output for the same input (deterministic)

- It does not read from or write to external state (no side effects)

- It does nothing other than compute a value (no observable effects)

 Now consider a React Function Component:

 

```jsx
  function   Greeting  (  {   name   }  )   { 
   const   [  count  ,   setCount  ]   =   useState  (  0  )  ; 
   const   theme   =   useContext  (  ThemeContext  )  ; 

   useEffect  (  (  )   =  >   { 
     document  .  title   =   `Hello, ${name}`  ; 
   }  ,   [  name  ]  )  ; 

   return   ( 
     <  h1   style  =  {  {   color  :   theme  .  primary   }  }  > 
       Hello  ,   {  name  }   (  {  count  }  ) 
     <  /  h1  > 
   )  ; 
 }
```

 This Component:

- reads internal state and receives an updater through useState

- reads external state from the component tree through useContext

- schedules a side effect through useEffect

 This is not a morphism in Set .
It reads things other than its argument (props), and it does things other than compute a pure value.

 A React Component is not a "pure function" in the mathematical sense.

 Then why does React call Components "pure"?
Because React uses the word "pure" in a different sense .
In React, "pure" means:

> Having no observable side effects during rendering - more precisely, behaving correctly inside React's effect system.

 This is a much weaker condition than mathematical purity, and confusing these terms leads to a fundamental misunderstanding.

# The Original Meaning of "Idempotent"

 React's documentation says the following ([Components and Hooks must be pure](https://react.dev/reference/rules/components-and-hooks-must-be-pure)):

> "Components must be idempotent - React components are assumed to always return the same output with respect to their inputs - props, state, and context."

 What does "idempotent" mean mathematically here?

## Idempotence in Mathematics

 The definition of an idempotent element in algebra is:

> Definition (idempotent element). In a monoid (M, ·, e) , an element a ∈ M is idempotent if it satisfies a · a = a .

 Extending this to functions:

> Definition (idempotent endomorphism). In a category 𝒞 , a morphism e: A → A is idempotent if it satisfies e ∘ e = e .

 These two definitions follow [Eric W. Weisstein, "Idempotent," MathWorld](https://mathworld.wolfram.com/Idempotent.html) for idempotent elements and [Emily Riehl, Category Theory in Context , Example 3.2.14](https://emilyriehl.github.io/files/context.pdf) for idempotent endomorphisms.

 Concrete examples:

- The absolute value function is idempotent: ||x|| = |x|

- A projection matrix P is idempotent: P^2 = P

- Math.floor is idempotent: Math.floor(Math.floor(x)) === Math.floor(x)

 What matters here is that idempotence is a property of an endomorphism `f: A -> A` .
Applying `f` once more to the output of `f` does not change the result - this is the original meaning of idempotence.

## React's "Idempotence" Is Not Mathematical Idempotence

 When React says a Component is "idempotent," it means "it returns the same output for the same input."
Mathematically, this is not idempotence.
It should be called determinism or well-definedness .

 Why?

- The type of a Component is Props -> VDOM , and Props != VDOM . In other words, it is not even an endomorphism.

- To verify f ∘ f = f , we need to pass the output of f back into f as input. But passing a Component's output (VDOM) into the Component's input (Props) has no meaning.

- What React is saying is " f(x) = f(x) (the same input gives the same output)," not " f(f(x)) = f(x) ."

 `f(x) = f(x)` is a property every function should satisfy by definition, and it is not something we would go out of our way to call "idempotence." More precisely, what React intends is probably that "even if Hooks have internal state, the Component returns the same VDOM for the same tuple of (props, state, context)." But this is a "deterministic function," not an "idempotent" one.

## The Rendering Operation Can Be Expressed as Idempotent

 However, if we shift our point of view, React does contain an operation that can be expressed as idempotent.

 Fix a state `s`, set aside user Effects and external I/O for the moment, and look only at the DOM state.
Then consider the composition of rendering and committing as a single operation:

 u s : D O M → D O M u s = commit ⁡ ( reconcile ⁡ ( render ⁡ ( s ) ) ) \begin{array}{c}
u_{s}: \mathrm{DOM} \to \mathrm{DOM}
\\
u_{s} = \operatorname{commit}(\operatorname{reconcile}(\operatorname{render}(s)))
\end{array} u s ​ : DOM → DOM u s ​ = commit ( reconcile ( render ( s ))) ​
 Then:

 u s ( u s ( dom ⁡ ) ) = u s ( dom ⁡ ) u_{s}(u_{s}(\operatorname{dom})) = u_{s}(\operatorname{dom}) u s ​ ( u s ​ ( dom )) = u s ​ ( dom )
 Applying render and commit twice for the same state yields the same DOM state as applying them once, if we look only at the DOM state.
If there is no diff, the second application can be treated as a no-op.
 This is idempotence when viewed as a DOM state transformation.

 In other words, what should be treated as idempotent in React is not the Component function itself , but the idealized render-and-commit operation `u_s`.
This distinction is decisive.

# React Fiber and Algebraic Effects

 Now let us turn to React's internal structure.

 React Fiber - React's core runtime - has features that resemble Algebraic Effects.
Dan Abramov also introduces algebraic effects as a way to think about some things React does ([Dan Abramov, "Algebraic Effects for the Rest of Us"](https://overreacted.io/algebraic-effects-for-the-rest-of-us/), 2019). The same article explicitly calls the connection to React "a stretch," says Suspense is not an algebraic effect per se, and notes that JavaScript cannot really resume execution later.

## What Are Algebraic Effects?

 Algebraic effects are a mathematical framework for separating computation from effects (side effects).
The general explanation in this section follows [Plotkin and Power, "Algebraic Operations and Generic Effects"](https://doi.org/10.1023/A:1023064908962) (2003).

 The basic structure consists of three elements:

- Effect signature : the set of available operations

- Computation : a program that may call effect operations

- Handler : an interpreter that gives meaning to effect operations

 This is not React's actual implementation, but pseudocode for explaining the correspondence:

 

```text
 // Effect signature
effect GetState  : Unit -> State
effect SetState  : State -> Unit
effect ReadProps : Unit -> Props
effect ReadContext: Key -> Value
effect Suspend   : Promise<A> -> A
effect Throw     : Error -> bottom

// Handler (= React Fiber runtime)
handler ReactFiber {
  return vdom -> vdom
  ReadProps(_, resume)      -> resume(currentProps)
  GetState(_, resume)       -> resume(currentFiber.memoizedState)
  SetState(newState, resume) -> enqueueUpdate(newState); resume(unit)
  Suspend(promise, retryRender) -> showFallback(); promise.then(() -> retryRender())
  Throw(error, _)           -> propagateToErrorBoundary(error)
}
```

 Here the relationship between the React Function Component written by the user and the React Fiber runtime can be mapped as follows:

 Role in algebraic effects
 Correspondence in React

 Effect signature
 Declaration of available operations
 Hooks API (`useState`, `useContext`, `use`, ...)

 Computation
 Program that calls effect operations
 User-written Function Component

 Handler
 Interpreter that gives meaning to operations
 React Fiber runtime

 In this correspondence, React Hooks can be read as effect operations:

 Hook
 Effect operation
 Handler

 `useProps`
 `ReadProps`
 Current props

 `useState`
 `GetState / SetState`
 Fiber's state queue

 `useContext`
 `ReadContext`
 Provider chain lookup

 `use(promise)`
 `Suspend`
 Suspense boundary

 `throw error`
 `Throw`
 Error boundary

 `useEffect`
 `ScheduleEffect`
 Effect queue in commit phase

 Here `useProps` is not a real React API. In the rest of this essay, I will generalize props - normally received as a Component function argument - as a conceptual Hook operation that reads the current props from the handler.

 A user-written Component can be viewed as an effectful computation, and React Fiber as its handler (interpreter).

 However, this is not a claim that algebraic effects alone explain all of React. In particular, the static shape of the Hook call sequence required by the Rules of Hooks is hard to capture using only ordinary monads or algebraic effects. The order should be: the Rules of Hooks come first, constraining the shape of the Component body; as a result, the Hook call sequence can be embedded fairly faithfully into an Applicative / Free Applicative-like structure.

# Function Composition in the Kleisli Category

 The "function composition" implicitly assumed by "UI = f(State)" also needs to be examined mathematically.

## Kleisli Category

 Given a monad `T` on a category `𝒞`, we can construct the Kleisli category `𝒞_T`.
Here I mean a categorical monad: an endofunctor `T: 𝒞 → 𝒞` together with natural transformations `η: Id ⇒ T` (unit) and `μ: T² ⇒ T` (multiplication), forming a triple `(T, η, μ)` that satisfies the monad laws. For the definitions of monad and Kleisli category, see [Emily Riehl, Category Theory in Context , Definition 5.1.1 and Definition 5.2.10](https://emilyriehl.github.io/files/context.pdf):

- Objects : the same as 𝒞

- Morphisms : a morphism A -> B in 𝒞_T is a morphism A -> T(B) in 𝒞

- Composition : for f: A -> T(B) and g: B -> T(C) , their Kleisli composition is:

 g ∘ T f = μ C ∘ T ( g ) ∘ f g \circ_{T} f = \mu_{C} \circ T(g) \circ f g ∘ T ​ f = μ C ​ ∘ T ( g ) ∘ f
 That is:

 A → f T ( B ) → T ( g ) T ( T ( C ) ) → μ C T ( C ) A \xrightarrow{f} T(B) \xrightarrow{T(g)} T(T(C)) \xrightarrow{\mu_{C}} T(C) A f ​ T ( B ) T ( g ) ​ T ( T ( C )) μ C ​ ​ T ( C )

## A React Component Is a Kleisli Morphism

 From this point on, this is not an official formal semantics of React.
It is a sketch for reading React's different effects through one abstract effect monad.
Let `R` be that hypothetical React effect monad.
If we follow the surface syntax of JavaScript, the type of a React Component can be read as:

 C o m p o n e n t : P r o p s → R ( V D O M ) \mathrm{Component}: \mathrm{Props} \to R(\mathrm{VDOM}) Component : Props → R ( VDOM )
 This is a way to read it as a morphism `Props -> VDOM` in the Kleisli category `Set_R`. However, if we want to handle the program structure of Hook operations uniformly, props can also be moved inside the computation as a conceptual Hook operation:

 useProps ⁡ : R ( P r o p s ) \operatorname{useProps}: R(\mathrm{Props}) useProps : R ( Props )
 In this reading, `Props -> R(VDOM)` is the expression where props are supplied first, while `R(VDOM)` with `useProps` is the expression where React Fiber supplies props during interpretation.

 Reading it as a Kleisli morphism (an effectful computation), rather than as a Set morphism (a pure function), is closer to React's behavior.

## Component Composition

 Consider component composition in JSX:

 

```jsx
  function   Parent  (  {   data   }  )   { 
   const   processed   =   use  (  processData  (  data  )  )  ; 
   return   <  Child   items  =  {  processed  }   /  >  ; 
 }
```

 If we abstract this dependency, we can sketch it as Kleisli composition:

 P a r e n t = C h i l d ∘ R p r o c e s s \mathrm{Parent} = \mathrm{Child} \circ_{R} \mathrm{process} Parent = Child ∘ R ​ process
 Here `∘_R` is not ordinary composition `∘` in Set , but Kleisli composition for the abstracted React effect monad.
Because it passes through a call to `use` - that is, an effect corresponding to Suspend - it is hard to express as pure function composition.

 In other words, if we include Hooks and Suspense, "function composition" in React cannot be fully captured by ordinary function composition alone.
This is another reason why "UI = f(State)" is not naively correct.

## Monad Bind and an Applicative Skeleton - What a Component Body Really Is

 Now that we understand Kleisli composition, let us dig one layer deeper into what is happening inside the function body of a Component .

 For a monad `T`, the bind operation (written `>>=` in Haskell) has the following type:

 bind ⁡ T : T ( A ) × ( A → T ( B ) ) → T ( B ) \operatorname{bind}_{T}: T(A) \times (A \to T(B)) \to T(B) bind T ​ : T ( A ) × ( A → T ( B )) → T ( B )
 It is the operation that "takes the result of an effectful computation and passes it to the next effectful computation."
Haskell's do notation is syntactic sugar for writing chains of bind in a readable way:

 

```haskell
  -- do notation 
 do 
   state   <  -   getState 
   ctx     <  -   readContext   themeCtx 
   pure   (  view   state   ctx  ) 

 -- Desugared (chain of bind) 
 getState      >  >  =  \ state   -  > 
 readContext   themeCtx   >  >  =  \ ctx   -  > 
 pure   (  view   state   ctx  )
```

 This perspective is useful when reading a React Component body as a computation that calls effects in order and returns VDOM from their results. If we also include `useProps` in the abstraction, for example:

 

```jsx
  function   Component  (  )   { 
   const   props   =   useProps  (  )  ;   // conceptual Hook operation: ReadProps >>= \props -> 
   const   [  state  ,   setState  ]   =   useState  (  init  )  ;   // <- bind: GetState >>= \state -> 
   const   ctx   =   useContext  (  ThemeCtx  )  ;   // <- bind: ReadContext >>= \ctx -> 
   return   <  View   name  =  {  props  .  name  }   state  =  {  state  }   ctx  =  {  ctx  }   /  >  ;   // <- pure: return (View props state ctx) 
 }
```

 Locally, the body of a React Component can be read as something close to do notation for the React effect monad.

 There is an important caveat, though. An ordinary monad is too expressive to represent React's requirement that the Hook call sequence have a static shape. With bind, the result of an earlier computation can decide the very shape of the effects that run next:

 

```haskell
  do 
   x   <  -   action1 
   if   condition   x 
     then   do   {   y   <  -   action2  ;   pure   (  f   x   y  )   }    -- action2 is present 
     else   pure   (  g   x  )                            -- action2 is absent
```

 This is natural to write as monadic computation. But React Hooks specifically forbid changing the shape of the Hook sequence based on values or branches.

 The property "the shape of the effects is known first, and only the values flow in later" is closer to Applicative than to Monad. An Applicative `F` roughly has these operations:

 pure ⁡ F : A → F ( A ) ap ⁡ F : F ( A → B ) × F ( A ) → F ( B ) \begin{array}{c}
\operatorname{pure}_{F}: A \to F(A)
\\
\operatorname{ap}_{F}: F(A \to B) \times F(A) \to F(B)
\end{array} pure F ​ : A → F ( A ) ap F ​ : F ( A → B ) × F ( A ) → F ( B ) ​
 Here `ap_F` corresponds to ` ` in Haskell.

 An Applicative does not have a bind-like `F(A) -> (A -> F(B)) -> F(B)`. Therefore, the result of a previous effect cannot choose the structure of later effects. Instead, the skeleton of which effects are used, and in which order, is fixed statically, and their results are fed into a pure function .

 For a Component that satisfies the Rules of Hooks, we can very roughly sketch the Hook call sequence in an Applicative-like form:

 

```haskell
  pure   view   <  *  >   useProps   <  *  >   useState   init   <  *  >   useContext   themeCtx
```

 This is not React's implementation. But once props are also included as the conceptual Hook `useProps`, an Applicative skeleton is closer than a chain of bind as a structural sketch of "the input and Hook sequence are fixed, and JSX is constructed from the values obtained from them."

### The Rules of Hooks Make an Applicative Skeleton Possible

 Now reconsider React's [Rules of Hooks](https://react.dev/reference/rules/rules-of-hooks):

> Do not call Hooks inside loops, conditions, or nested functions Hooks must always be called at the top level of a Function Component

 The order matters here. The rule comes first. Rather than saying that "the Applicative expression explains the Rules of Hooks," it is better to say that the Rules of Hooks constrain the shape of the Component body enough that it can be embedded into an Applicative skeleton of Hook operations, including `useProps` .

 By "faithful embedding" here, I only mean that the number and order of Hook calls can be extracted as program structure without being lost.

 The React equivalent is forbidden :

 

```jsx
  // NG: Hook inside a conditional branch 
 function   Component  (  {   condition   }  )   { 
   const   [  x  ]   =   useState  (  0  )  ; 
   if   (  condition  )   { 
     const   y   =   useContext  (  Ctx  )  ;   // <- Rules of Hooks violation 
     return   <  A   x  =  {  x  }   y  =  {  y  }   /  >  ; 
   } 
   return   <  B   x  =  {  x  }   /  >  ; 
 }
```

 Why?
React Fiber stores the order of Hook calls as a linked list.
If the number or order of Hook operations changes from render to render, Fiber cannot correctly line up the previous render's result with the current Hook calls.

 On the other hand, it is fine to fix the Hook sequence first and then branch in the UI returned from the resulting values:

 

```jsx
  // OK: the Hook sequence is fixed 
 function   Component  (  {   condition   }  )   { 
   const   [  x  ]   =   useState  (  0  )  ; 
   const   y   =   useContext  (  Ctx  )  ; 
   return   condition   ?   <  A   x  =  {  x  }   y  =  {  y  }   /  >   :   <  B   x  =  {  x  }   /  >  ; 
 }
```

 In other words, what React needs to keep static is not "the rendering result that uses values," but the program structure of Hook operations . Because the Rules of Hooks fix that shape first, it becomes possible to map it into a structure such as `FreeApplicative HookOp`, or, if we also include the recursion of the component tree, something like `Fix (FreeApplicative HookOp)`.

 A related experimental implementation is [ubugeeei/mreact](https://github.com/ubugeeei/mreact).
It expresses React Hooks as an indexed monad in Haskell, representing the Hook call order as a type-level list so that the Rules of Hooks can be handled by the type checker. In the framing of this essay, that type-level Hook list is better understood not as an expression attached to React after the fact, but as a capture of the program shape that the Rules of Hooks already force: a static skeleton closer to Applicative / Free Applicative structure.

# use and Suspense - A Concrete Form That Resembles Algebraic Effects

 The `use` Hook and `Suspense` are where the algebraic-effects-like behavior in React is easiest to see.
However, this does not mean that React's implementation has real algebraic effects.

 

```jsx
  function   UserProfile  (  {   userId   }  )   { 
   const   user   =   use  (  fetchUser  (  userId  )  )  ; 
   return   <  div  >  {  user  .  name  }  <  /  div  >  ; 
 } 

 function   App  (  )   { 
   return   ( 
     <  Suspense   fallback  =  {  <  Loading   /  >  }  > 
       <  UserProfile   userId  =  {  1  }   /  > 
     <  /  Suspense  > 
   )  ; 
 }
```

 We can describe this mechanism with the vocabulary of algebraic effects:

 1. `use(promise)` corresponds to performing an effect operation:

 If the Promise is unresolved, the public React API says that the Component suspends (`use` integrates with [Suspense](https://react.dev/reference/react/use)).
This can be read as a non-local control flow resembling a "call to an operation" in algebraic effects.

 2. `Suspense` corresponds to an effect handler:

 `Suspense` handles the suspension, displays the fallback UI, and retries rendering after the Promise resolves.

 3. On re-render, `use(promise)` returns the resolved value:

 This resembles the algebraic-effects operation of "passing a value to the continuation and resuming it."
However, React is not actually saving the JavaScript execution stack and resuming from that point.
It re-renders the Component tree after the Promise resolves.
This point follows the [React Suspense documentation](https://react.dev/reference/react/Suspense) and Dan Abramov's caveat in ["Algebraic Effects for the Rest of Us"](https://overreacted.io/algebraic-effects-for-the-rest-of-us/).

 In pseudo handler notation:

 

```text
 handle(UserProfile(userId)) with {
  return vdom -> vdom
  Suspend(promise, retryRender) ->
    display <Loading />;
    await promise;
    retryRender()  // <- re-render, not a real continuation resume
}
```

 What is especially important here is that `use` can suspend a Component's render, and React can re-render it later .

 An ordinary JavaScript function runs to completion once called.
With `async` / `await`, execution can continue from an `await` point, but React Components are not written as `async function`.
Even so, React uses Suspense boundaries and re-rendering to create the experience that it "waited there and continued once the value arrived."
This is what makes the behavior reminiscent of algebraic effects (or delimited continuations).

# The Mistake of Client-Server "Isomorphism"

 There are terms such as "Isomorphic JavaScript" and "Universal JavaScript."
They are also often used in the context of Server Components, but is this "isomorphism" mathematically correct?

## Isomorphism in Category Theory

> Definition (isomorphism). In a category 𝒞 , a morphism f: A → B is an isomorphism if there exists a morphism g: B → A such that g ∘ f = id_A and f ∘ g = id_B .

 This definition follows [Emily Riehl, Category Theory in Context , Definition 1.1.10](https://emilyriehl.github.io/files/context.pdf).

 An isomorphism means a reversible transformation that preserves structure.
If `A` and `B` are isomorphic, then they cannot be distinguished category-theoretically.

## Server Rendering and Client Rendering Are Not Isomorphic

 Consider server rendering and client rendering as functors:

 F S : C o m p o n e n t → H T M L F C : C o m p o n e n t → D O M \begin{array}{c}
F_{S}: \mathrm{Component} \to \mathrm{HTML}
\\
F_{C}: \mathrm{Component} \to \mathrm{DOM}
\end{array} F S ​ : Component → HTML F C ​ : Component → DOM ​
 To begin with, `HTML != DOM`.
Since the output categories are different, there is no room to construct an isomorphism between `F_S` and `F_C`.

 A transformation from an HTML string to the DOM (parsing) exists, but the reverse transformation (DOM -> HTML) is serialization.
The composition of these two is not necessarily the identity morphism, because event handlers, internal state, closures, and so on are lost.

## A More Accurate Description: Different Effect Handlers

 In the framework of algebraic effects, server rendering and client rendering can be understood as different handlers for the same effectful computation :

 C o m p o n e n t : P r o p s → E f f R e a c t ( V D O M ) h a n d l e S e r v e r : E f f R e a c t ( V D O M ) → H T M L S t r i n g h a n d l e C l i e n t : E f f R e a c t ( V D O M ) → D O M M u t a t i o n s \begin{array}{c}
\mathrm{Component}: \mathrm{Props} \to \mathrm{Eff}_{\mathrm{React}}(\mathrm{VDOM})
\\
\mathrm{handleServer}: \mathrm{Eff}_{\mathrm{React}}(\mathrm{VDOM}) \to \mathrm{HTMLString}
\\
\mathrm{handleClient}: \mathrm{Eff}_{\mathrm{React}}(\mathrm{VDOM}) \to \mathrm{DOMMutations}
\end{array} Component : Props → Eff React ​ ( VDOM ) handleServer : Eff React ​ ( VDOM ) → HTMLString handleClient : Eff React ​ ( VDOM ) → DOMMutations ​
 As the [React documentation](https://react.dev/reference/rsc/use-client) explains, the difference between Server Components and Client Components appears as a difference in execution environment and available APIs.
In this essay's reading, we can understand that as a difference in available effect signatures :

- Server Component : can directly use server-side operations such as DB queries and file system access. Cannot use many Hooks such as useState and useEffect .

- Client Component : can use client-side APIs such as useState and useEffect . Cannot directly bring server-only code into the Client module subtree.

 This is not an isomorphism.
It should be understood as an inclusion relation or subtyping between effect signatures.

 S e r v e r E f f e c t s ≠ C l i e n t E f f e c t s S h a r e d E f f e c t s = S e r v e r E f f e c t s ∩ C l i e n t E f f e c t s \begin{array}{c}
\mathrm{ServerEffects} \neq \mathrm{ClientEffects}
\\
\mathrm{SharedEffects} = \mathrm{ServerEffects} \cap \mathrm{ClientEffects}
\end{array} ServerEffects  = ClientEffects SharedEffects = ServerEffects ∩ ClientEffects ​
 The shared portion works as Components that can become either Server Components or Client Components depending on usage.
Server-only operations are available only on the server side, and client-only operations are available only on the client side.
This is not "isomorphism," but compatibility based on partial overlap between effect signatures.

# Conclusion: Rewriting UI = f(State)

 Let us summarize the discussion so far.

## Problems with the Naive Equation

 U I = f ( S t a t e ) \mathrm{UI} = f(\mathrm{State}) UI = f ( State )
 Problems with this equation:

- f is not a pure function - it executes effects through Hooks

- The word "idempotent" is misused - the Component function is not mathematically idempotent (the rendering operation can be expressed as idempotent)

- Composition cannot be captured by ordinary function composition alone - effect interpretation can be expressed as Kleisli composition, while the Hook sequence fixed by the Rules of Hooks is more naturally viewed as Applicative structure

- Client-Server is not an isomorphism - they can be expressed as different effect handlers

## A More Accurate Description

 In this essay's reading, at the level of JavaScript's surface syntax, a React Component can be expressed as a Kleisli morphism of the effect monad `R`:

 C o m p o n e n t : P r o p s → R ( V D O M ) \mathrm{Component}: \mathrm{Props} \to R(\mathrm{VDOM}) Component : Props → R ( VDOM )
 However, if we want to handle the program structure of Hook operations uniformly, props should be moved inside as a conceptual Hook operation rather than kept only as an external argument:

 useProps ⁡ : R ( P r o p s ) \operatorname{useProps}: R(\mathrm{Props}) useProps : R ( Props )
 In that case, the equation above captures the aspect that a Component is an effectful computation interpreted by the React runtime. It does not by itself capture the static Hook sequence required by the Rules of Hooks. For the program structure of Hook operations, the Rules of Hooks fix the shape first. Because of that constraint, the structure can be mapped into an Applicative / Free Applicative-like skeleton that also includes `ReadProps`:

 H o o k P r o g r a m   A ≈ F r e e A p p l i c a t i v e ( H o o k O p )   A \mathrm{HookProgram}\ A \approx \mathrm{FreeApplicative}(\mathrm{HookOp})\ A HookProgram   A ≈ FreeApplicative ( HookOp )   A
 UI generation can be expressed as interpretation by an effect handler `h`:

 U I = h p r o p s ( C o m p o n e n t P r o g r a m ) \mathrm{UI} = h_{\mathrm{props}}(\mathrm{ComponentProgram}) UI = h props ​ ( ComponentProgram )
 Here:

- ComponentProgram: HookProgram(VDOM) is the description of the effectful computation written by the user, including useProps , useState , useContext , and so on

- h_props: HookProgram(VDOM) -> DOM is an expression of the React Fiber runtime interpreting that computation while supplying the current props

 And if we set aside user Effects and external I/O and view it as a DOM state transformation, the rendering operation `u_s = h(render(s))` can be expressed as an idempotent endomorphism on the DOM:

 u s ( u s ( dom ⁡ ) ) = u s ( dom ⁡ ) u_{s}(u_{s}(\operatorname{dom})) = u_{s}(\operatorname{dom}) u s ​ ( u s ​ ( dom )) = u s ​ ( dom )

 U I = f ( S t a t e ) \mathrm{UI} = f(\mathrm{State}) UI = f ( State )
 is useful as an educational intuition, but if we look at React's behavior more carefully, it needs some qualification.

 A React Component is not a pure function in the mathematical sense.
The aspect interpreted by React Fiber can be expressed as an effectful computation in an algebraic effect system. At the same time, this expression does not explain the static Hook sequence first. The Rules of Hooks constrain the program shape first, and because of that constraint the program can be mapped fairly faithfully into an Applicative / Free Applicative-like structure that includes props as `useProps`.

 U I = R e a c t H a n d l e p r o p s ( C o m p o n e n t P r o g r a m ) \mathrm{UI} = \mathrm{ReactHandle}_{\mathrm{props}}(\mathrm{ComponentProgram}) UI = ReactHandle props ​ ( ComponentProgram )
 With this understanding, React's "rules," the behavior of Hooks, the mechanism of `use` and Suspense, and the design principles of Server Components become easier to reason about in two layers: interpretation of effects and a static Hook skeleton .

### Related

- [Our Achievements Stand on Remains, Including the Work of Those Before Us](/en/posts/30) #oss #ai #software
- [Is ‘It Is OSS, So Just Participate’ Really A Valid Argument?](/en/posts/25) #oss #philosophy #community
- [In the Age of AI, Rethink Yesterday's Logic](/en/posts/24) #philosophy #ai #software
- [For-Profit Companies Should Pay the People Who Build OSS](/en/posts/21) #oss #philosophy #sponsorship
- [corsa-bind: The Idea of Language Processor Orchestration](/en/posts/17) #typescript #language #compiler
- [Signals and Signals. And Retained UI.](/en/posts/12) #javascript #oss #signals

[← Back to all posts](/en)

## Sitemap

- [Browse every page on wtrclred](https://wtrclred.vercel.app/sitemap.md)
