Blog

use(): the React new experimental hook ๐Ÿš€

31 Oct, 2022
Xebia Background Header Wave

React team and the JavaScript community are discussing a hook called use and I see a lot of hype about this new feature. See how to implement it and the possibilities for the near future. ๐Ÿ”ฎ

React has a GitHub repo called RFC that stands for request for comments.
It’s a great place where you can interact discussing the new features that the React team has intention to add into the React core or simply discuss ideas suggested by the community.

And one specifically has numerous interactions called:

First class support for promises and async/await

 

What does that mean?

โ€” First class support โ€“ means the code that you are creating can be used as a variable on the root level of your application.

โ€” promises and async/await โ€“ functions that handle heavy tasks or external calls.

So basically, we are talking about using promises on the root level of your application and in a React case use promises inside components directly.

This opens doors to countless possibilities like to fetch server data before rendering the component, but let’s see the first benefit that will affect most of the developers, that is: reduce boilerplate fetching data.

Just a disclaimer:
It’s still an experimental feature, so hold your horses to use it in production because the API might change or even not be included in the next React version, but is a great opportunity to test in development to check the possibilities.

 

Prepare the project

I’m using a Vite + React boilerplate project with typescript.

# terminal
yarn create vite

 

To have access to this new features, we have to install the experimental version of React and React-DOM.

# terminal inside your project folder
yarn add react@experimental react-dom@experimental

 

Add the experimental type; otherwise, typescript will complain that the new use hook doesn’t exist.

// tsconfig.json
"compilerOptions": {
  // ... other configs 
  "types": ["react/experimental"]
}

 

[Before] How do we fetch data nowadays?

Inside the src/App.tsx, let’s paste a common fetch request.

  // src/App.tsx
  import { useEffect, useState } from "react";

  type Product = {
    title: string
  }

  function App() {
    const [product, setProduct] = useState<Product>();

    useEffect(()=>{
      fetch('https://dummyjson.com/products/1')
        .then(res => res.json())
        .then(json => setProduct(json))
    },[])

    if(!product) return <div>Loading...</div> 

    return (
      <div>{product.title}</div>
    )
  }

  export default App

 

[After] What the new use hook looks like?

  // src/App.tsx
  import { use } from "react";

  type Product = {
    title: string
  }

  const getProduct = fetch('https://dummyjson.com/products/1').then(res => res.json())

  function App() {
    const product = use<Product>(getProduct)
    if(!product) return <div>Loading...</div> 

    return (
      <div>{product.title}</div>
    )
  }

  export default App

 

Clearly, we can see some great benefits like:

  • no useState
  • no useEffects
  • simpler API

 

But there’s another hidden behaviour.

If we add a console.log in our product variable like this:

const product = use<Product>(getProduct)
console.log(product)

 

We will see that product is never undefined.

Another interesting thing is that since this hooks happens before the component rendering, it also allows adding if statements before defining the hook like this.

  // src/App.tsx
  import { use } from "react";

  type Product = {
    title: string
  }

  const getProduct = fetch('https://dummyjson.com/products/1').then(res => res.json())
  const beforeHook = false

  function App() {
    if(beforeHook) return <div>if before hooks are also ok</div>
    const product = use<Product>(getProduct)
    if(!product) return <div>Loading...</div> 

    return (
      <div>{product.title}</div>
    )
  }

  export default App

New possibilities

The reason is that this hook happens before the first render, which means that react can offer support
โ€” to server-side components, simply adding this call into your component
โ€” break this React component into another chunk, simply adding async

Unknowns

The community is still deciding
โ€” how to handle errors
โ€” if they will add state controls like โ€œpendingโ€, โ€œrejectedโ€
โ€” people that disagree about this concept because it adds complexity inside React that intends to be a library and not a framework.

Conclusion

In the end, React team and community are pushing hard to come up with better solutions for fetching and server components, which means that soon we will have a way simpler solution to control fetch data natively with server components support.

 

Upcoming Meetups

We also have 2 great Javascripts meetups coming up soon:

  • Wednesday, Nov 9 โ€“ย AdvancedJS Amsterdamย (Wibaut Office) hosted by Marten de Groot
  • Wednesday, Nov 16 โ€“ย JS Eindhovenย (Microlab office) hosted by Hernani Fernandes
Hernani Fernandes
Senior Frontend Engineer - Work hard, play hard
Questions?

Get in touch with us to learn more about the subject and related solutions

Explore related posts