Skip to content

Importing useId from React breaks on React 17 #1278

@huyenltnguyen

Description

@huyenltnguyen

Bug report

Packages affected

  • sandpack-client
  • sandpack-react

Description of the problem

My project is still on React 17 and I ran into this error when installing the latest @codesandbox/sandpack-react (v2.20.0):

Generating development JavaScript bundle failed

export 'useId' (imported as 'useId') was not found in 'react' (possible exports: Children, Component, Fragment, Profiler,
PureComponent, StrictMode, Suspense, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, cloneElement, createContext,
createElement, createFactory, createRef, forwardRef, isValidElement, lazy, memo, useCallback, useContext, useDebugValue,
useEffect, useImperativeHandle, useLayoutEffect, useMemo, useReducer, useRef, useState, version)

This happens because useId is imported directly from React:

import { useId as useReactId } from "react";
import { generateRandomId } from "./stringUtils";
export const useSandpackId = () => {
if (typeof useReactId === "function") {
/* eslint-disable-next-line */
return useReactId();
} else {
return generateRandomId();
}
};

In ES modules, named imports must exist at import time. But React 17 doesn't export useId, so the import fails at build time before the fallback in useSandpackId can run.

Solution

I'd suggest changing the useId import to:

import React from "react";
const useReactId = React.useId;

This way, useReactId will be undefined on older React versions and the existing fallback to generateRandomId() will work as intended.

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