Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import React experimental hooks correctly?

Tags:

npm

reactjs

I'm trying to learn and some of the unreleased "unstable" features of React. In particular, I want to use the "useEffectEvent" hook.

The problem is that I can't import that part of the package in any way.

When I try to import something from the React official package in this way:

import * as React from "react"

The module automatically points to this directory (the @types/react npm package)

node_modules/@types/react/index"

The experimental hooks (such as "React.experimental_useEffectEvent") are here though:

node_modules/react/index"

This happens both with CRA and Vite, and I tried with standard JS builds (no TS, no tsconfig file).

How can I reach that part of React's code? Thanks

like image 773
fra.mstr Avatar asked Jun 28 '26 19:06

fra.mstr


1 Answers

There are two (or three) aspects of this (both shown in the documentation, though #2 is a bit subtle [it's at the top, but not in the code sample]):

  1. You have to be using the react@experimental and react-dom@experimental modules.
  2. The hook's name is experimental_useEffectEvent, not just useEffectEvent.

So:

import { experimental_useEffectEvent } from "react";
// ...
experimental_useEffectEvent(/*...*/);

or perhaps (for now):

import { experimental_useEffectEvent as useEffectEvent } from "react";
// ...
useEffectEvent(/*...*/);

Codesandbox example

If you're using TypeScript, you'll want to read the instructions in the @types/react module's experimental.d.ts file to see how to get TypeScript to recognize the experimental hooks. There are a couple of different ways; one of the simpler ones is to add this to any file in the project (I used App.tsx):

/// <reference types="react/experimental" />

FWIW, here's how I bootstrapped a new project using the experimental features:

  1. npm create vite@latest (I use Vite.js as my bundler).
    • Chose React from the list
    • Chose TypeScript from the list
  2. npm install react@experimental react-dom@experimental
  3. Replaced the pre-supplied App.tsx with:
    /// <reference types="react/experimental" />
    import { experimental_useEffectEvent as useEffectEvent } from "react";
    import "./App.css";
    
    function App() {
        return <div>typeof useEffectEvent: {typeof useEffectEvent}</div>;
    }
    
    export default App;
    

When I run that, I get typeof useEffectEvent: function on the page.

I don't use create-react-app, but I did briefly try it, but ran into dependency issues upgrading React to the experimental version.

like image 126
T.J. Crowder Avatar answered Jul 01 '26 10:07

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!