4

use(): the React new experimental hook

 1 year ago
source link: https://xebia.com/blog/use-hook-the-new-experimental-javascript-react-feature/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

use(): the React new experimental hook 🚀

This website stores cookies on your computer. These cookies are used to improve your website and provide more personalized services to you, both on this website and through other media. To find out more about the cookies we use, see our Cookie Statement and Privacy Statement.

We won't track your information when you decline. But in order to comply with your preferences, we'll have to use just one tiny cookie so that you're not asked to make this choice again.

Share
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"]
}
TypeScript

[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
TypeScript

[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
TypeScript

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)
TypeScript

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

TypeScript

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK