Skip to content

Proposal: add overloads to useRef type to match React's API #5056

Description

@ashunar0

Context

When using hono/jsx hooks to write code that mirrors React-style patterns, useRef returns a ref whose .current is always typed as T | null, even when initialized with a non-null value.

const ref = useRef(new Map<string, number>())
ref.current.set('a', 1) // ❌ TS error: 'ref.current' is possibly 'null'.

This is because useRef currently has a single signature:

// hono/src/jsx/hooks/index.ts
export declare const useRef: <T>(initialValue: T | null) => RefObject<T>
// where RefObject<T> = { current: T | null }

The runtime implementation always returns { current: initialValue }, so when a non-null initial value is passed, .current cannot actually be null at first read. The nullable type is purely a TypeScript-level limitation.

React behavior (for comparison)

React provides overloads so that useRef(value) returns a non-nullable ref, while useRef<T>(null) keeps the nullable shape needed for DOM refs:

function useRef<T>(initialValue: T): MutableRefObject<T>
function useRef<T>(initialValue: T | null): RefObject<T>
function useRef<T = undefined>(): MutableRefObject<T | undefined>

Proposal

Add matching overloads to hono/jsx's useRef so that users get non-nullable .current when they pass a non-null initial value. Implementation does not need to change — this is a type-only fix.

I'm happy to submit a PR if this direction is welcome. Wanted to check first whether the single-overload signature was intentional (e.g. simpler types by design) before opening one.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions