Skip to content

feat(jsx): introduce hono/jsx/signal - #5657

Open
yusukebe wants to merge 12 commits into
v5from
feat/jsx-signal
Open

yusukebe wants to merge 12 commits into
v5from
feat/jsx-signal

Conversation

@yusukebe

@yusukebe yusukebe commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

This PR introduces Signals to Hono JSX.

import { render } from 'hono/jsx/dom'
import { signal, computed, effect } from 'hono/jsx/signal'

const Counter = () => {
  const count = signal(0)
  const double = computed(() => count.value * 2)

  effect(() => {
    console.log('count:', count.value)
  })

  return (
    <div>
      <p>
        {count} * 2 = {double}
      </p>
      <button onClick={() => count.value++}>+1</button>
    </div>
  )
}

render(<Counter />, document.getElementById('root')!)

Until now, to add client-side interactivity, users have needed to use hooks from hono/jsx/dom, which follow the React API. This is good, but there are two problems:

  1. Quality - There are many APIs, and the implementation is complex. This makes it easier to introduce bugs.
  2. Complexity - The API is complex. Users might want something simpler.

I've been using Hono JSX, including its client-side features, since v4 was released. During that time, I realized I wanted a lighter client-side implementation.

The main use cases for Hono JSX are:

  • Adding simple interactivity to SSR-generated HTML without hydration.
  • Adding interactivity to only specific parts of a page using islands, like HonoX.

For these use cases, I think hooks are too heavy.

That's why I want to introduce Signals.

The Signals API is simple, and its implementation requires much less code compared to React-style hooks. I think Signals are a great fit for Hono JSX.

This PR introduces Signals as an experimental feature in v5. If we agree with this direction, I'd like to recommend using Signals over hooks.

We put a lot of effort into implementing hooks, so it might be sad to move away from them. However, I think this could be a good decision for long-term maintainability.

The following is an AI-generated description:


Adds signals for Hono JSX as an experimental feature.

  • signal, computed, effect, batch and untracked from hono/jsx/signal
  • SSR renders the current value of a signal in children and attributes
  • hono/jsx/dom updates the text node or the attribute directly when a signal is passed as it is
  • Reading .value in a component re-renders only that component
  • signal(), computed() and effect() in a component are kept for each instance. No hooks are needed
  • effect() in a component does not run on the server
  • hono/jsx and hono/jsx/dom do not import hono/jsx/signal. They detect a signal with Symbol.for('hono.signal')

Breaking: the attribute types in JSX.IntrinsicElements are now T | SignalLike<T>. Added to docs/MIGRATION.md.

Size (minified): hono/jsx/signal is 1.8 KB. hono/jsx/dom grows by 0.8 KB.

The author should do the following, if applicable

  • Add tests
  • Run tests
  • pnpm run check:fix to format and lint the code
  • Add TSDoc/JSDoc to document the code

@pkg-pr-new

pkg-pr-new Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/hono@5657

commit: 635c79c

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.90993% with 74 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (v5@7a34a89). Learn more about missing BASE report.

Files with missing lines Patch % Lines
src/jsx/signal/index.ts 84.00% 52 Missing ⚠️
src/jsx/dom/render.ts 73.49% 22 Missing ⚠️
Additional details and impacted files
@@          Coverage Diff          @@
##             v5    #5657   +/-   ##
=====================================
  Coverage      ?   80.24%           
=====================================
  Files         ?      132           
  Lines         ?    10578           
  Branches      ?     2300           
=====================================
  Hits          ?     8488           
  Misses        ?     2090           
  Partials      ?        0           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yusukebe
yusukebe marked this pull request as ready for review November 19, 2026 00:52
@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@yusukebe

Copy link
Copy Markdown
Member Author

Hey @kotarotaniguchi0523 @ashunar0! Can you review this if you have time?

@ashunar0

Copy link
Copy Markdown
Contributor

@yusukebe sure! I'll check this tomorrow!

@kotarotaniguchi0523

Copy link
Copy Markdown

@yusukebe Me too! I'll check this tomorrow.

@ashunar0

Copy link
Copy Markdown
Contributor

I reviewed this. I think the direction of Signals is good. Here are some things I found while running it.

1. computed() stays subscribed to its sources, so it leaks memory

When a computed() is evaluated, it adds itself to the subscribers of its sources. It is removed only when a source changes. So on the server, a computed created for each request stays in a module-level signal.

const config = signal({ siteName: 'Hono' })

const Page = ({ path }: { path: string }) => {
  const title = computed(() => `${config.value.siteName} - ${path}`)
  return <title>{title}</title>
}

I rendered this 1000 times and ran GC. All 1000 objects captured by the computed were still alive. After writing to config, it went to 0. A signal like a server-side config rarely changes, so in practice it keeps growing.

The same happens on the DOM side. A computed in an unmounted component stays until its source changes, because disposing the scope cleans up only the effects.

In Preact, a computed subscribes to its sources only while it has its own subscribers (Computed.prototype._subscribe / _unsubscribe). Without subscribers, it checks whether it is stale by version numbers. I think we need the same approach, or at least both of these:

  • On the server, a computed does not subscribe to its sources
  • Disposing the scope on the DOM side also removes the computeds from their sources

2. A component that returns a signal directly throws on the server

const s = signal('hello')
const C = () => s

render(<C />, root)      // OK: hello
await (<C />).toString() // TypeError: str.search is not a function

It seems JSXFunctionNode does not handle a signal as the result.

3. precompile and the html helper do not support signals

jsxAttr('title', s)      // title="[object Object]"
jsxTemplate`<p>${s}</p>` // <p>[object Object]</p>

With "jsx": "precompile" (e.g. in Deno), JSX is compiled into these calls, so the output is the same.

4. effect() after await in an async component runs on the server

const Page = async () => {
  const data = await fetchData()
  effect(() => {
    console.log(data) // runs on the server
  })
  return <p>...</p>
}

signalHook.r sets the flag only synchronously, so the render after await is not treated as a server render. This effect is never disposed, so it also leaks like 1.

nit: subscribe() is not kept for each instance

signal(), computed() and effect() are kept for each instance, but subscribe() is not. If you call it in a component body, a new subscription is added on every render (after 3 re-renders, it was subscribed 4 times). Since the other three are kept, users may expect subscribe() to be kept too. It might be good to note this in the JSDoc, or to keep it for each instance in a component as well.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@yusukebe

Copy link
Copy Markdown
Member Author

Hey @ashunar0 !

Thank you for the review. These make sense to me. I fixed them with AI, but I understood what they did. Can you review this again?

  • 1. computed() leaks memory - c5f5df7 - A computed now subscribes to its sources only while it has subscribers, like Preact. Without subscribers, it checks the versions of its sources. Added tests with GC for both the server and the DOM.
  • 2. A component that returns a signal throws on the server - 19175de - JSXFunctionNode now handles a signal as the result.
  • 3. precompile and the html helper - 01d1d20 - jsxAttr and html render the current value of a signal.
  • 4. effect() after await in an async component - efc29c2 - Not fixed. We can't detect it without AsyncLocalStorage, so I added a note to the JSDoc of effect().
  • nit: subscribe() - d5ab3b7 - subscribe() is now an effect. In a component, it is kept for each instance and disposed on unmount.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@ashunar0

Copy link
Copy Markdown
Contributor

Thanks for the fixes! I checked them all, and they work. I also ran a fuzz test on the new computed and found no problems.

One small thing: an async component that returns a signal renders [object Object] on the server.

const s = signal('async')
const C = async () => s
await (<div><C /></div>).toString() // <div>[object Object]</div>

It's not in the types either, so I think it's fine to leave it unsupported.

LGTM!

@kotarotaniguchi0523

Copy link
Copy Markdown

Sorry for the delay! I think the overall direction looks good, but I have a couple of suggestions.

Proposal 1: Separate component setup from rendering

The JSDoc (L365–366) clearly states that signal(), computed(), and effect() must be called in the same order on every render.

However, if we accidentally change the call order by using a conditional branch, perComponent() (L47–49) may reuse the wrong signal without throwing an error.

Even though this restriction is documented, such mistakes can be difficult to notice. Could we remove this restriction itself?

My suggestion is to change the component execution logic in the DOM renderer to allow components to return a render function.

  • Run the outer function only once per mounted instance to initialize signals, computed values, and effects.
  • Run only the returned render function on updates.
  • Keep state through JavaScript closures.

With this approach, we could use conditional branches and loops during setup. We would also no longer need to manage state based on call order, including perComponent() and resetting observer.i.

Proposal 2: Reactive access to props

The current implementation uses callbacks from the latest render through the following code:

However, as described in the JSDoc for computed(), changes to regular props alone do not trigger reevaluation.

If we separate setup from rendering, could we use the existing signal mechanism to make the latest props available as reactive values inside computed values and effects defined during setup?

This would allow us to track props changes as dependencies without replacing callbacks on every render.

What do you think about these two proposals?

@github-actions

This comment has been minimized.

@yusukebe

Copy link
Copy Markdown
Member Author

Thank you @ashunar0 !!

One small thing: an async component that returns a signal renders [object Object] on the server.

I fixed it in 19e629f

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown

Bundle size check

main (a325a49) #5657 (4f1ec8d) +/-
Bundle Size (B) 20,323B 18,845B -1,478B
Bundle Size (KB) 19.85K 18.4K -1.45K

Compiler Diagnostics (tsc)

main (a325a49) #5657 (4f1ec8d) +/-
Files 83 84 +1
Lines 59,470 59,530 +60
Identifiers 60,683 61,879 +1,196
Symbols 106,553 115,720 +9,167
Types 163,319 171,802 +8,483
Instantiations 415,292 452,832 +37,540
Memory used 208,596K 193,805K -14,791K
I/O read 0.01s 0.01s 0s
I/O write 0s 0s 0s
Parse time 0.32s 0.29s -0.03s
Bind time 0.11s 0.11s 0s
Check time 1.33s 1.27s -0.06s
Emit time 0s 0s 0s
Total time 1.76s 1.67s -0.09s

Compiler Diagnostics (typescript-go)

main (a325a49) #5657 (4f1ec8d) +/-
Files 215 216 +1
Lines 121,032 121,092 +60
Identifiers 107,407 108,610 +1,203
Symbols 181,185 189,748 +8,563
Types 262,796 271,076 +8,280
Instantiations 623,102 660,538 +37,436
Memory used 154,276K 158,563K +4,287K
Memory allocs 1,785,586 1,851,961 +66,375
Config time 0.001s 0.001s 0s
BuildInfo read time 0s 0s 0s
Parse time 0.096s 0.088s -0.008s
Bind time 0s 0s 0s
Check time 0.467s 0.519s +0.052s
Emit time 0.005s 0.004s -0.001s
Changes compute time 0.041s 0.024s -0.017s
Total time 0.651s 0.672s +0.021s

Reported by octocov

@github-actions

Copy link
Copy Markdown

HTTP Performance Benchmark

Framework Runtime Average Ping Query Body
hono (origin/main) bun 89,581.32 100,260.42 88,817.43 79,666.12
hono (current) bun 101,086.36 112,845.28 99,710.26 90,703.55
Change +12.84% +12.55% +12.26% +13.85%

@yusukebe

Copy link
Copy Markdown
Member Author

Hey @kotarotaniguchi0523! Thank you for the review. Both concerns make sense!

But, I don't want to change the shape of a component to "a function that returns a render function". Hono JSX is based on the React-like syntax, and the new shape has its own pitfalls (forgetting () =>, destructuring props). So I addressed the two concerns without changing the API:

  • 1. A wrong call order is hard to notice - It now throws if the number or the kind of signal() / computed() / effect() calls changes between renders, like the hooks of React. It also logs the error with console.error, because the DOM renderer swallows an error in a re-render without an ErrorBoundary. Fixed in 307ebb4
  • 2. Props do not trigger re-evaluation - The computeds in a component are now evaluated again when the component is re-rendered, so they follow the props. An effect does not re-run on a re-render, but it can follow a prop through a computed: const current = computed(() => label). Fixed in 635c79c

What do you think?

@kotarotaniguchi0523

kotarotaniguchi0523 commented Nov 25, 2026 •

Copy link
Copy Markdown

Thank you for addressing my concerns!
If it can be fixed without changing the API, I think that is definitely the best approach. I'm sorry for my second suggestion in particular, as it lacked sufficient consideration on my end. I truly appreciate your thoughtful response to my poor review. It is a great honor for me to be involved in the implementation of hono/jsx/signal!
Please definitely continue with the direction of your commits!

@yusukebe

Copy link
Copy Markdown
Member Author

@kotarotaniguchi0523 Thank you. It was not a poor review at all!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants