React Just Got Even More Awesome

Dayvster 🌊 - Oct 15 '22 - - Dev Community

If you've worked on any react or next.js application in the past, you've probably noticed that it's very unopinionated in general, especially when it comes to how you handle async. Which played a big role in how we've fetched data in our react applications. So far we've either used useEffect, useSWR or more recently react-query. But now we're getting an exciting new feature in react that will make all things async especially data fetching a lot easier.

Introducing the use hook

More info here

Essentially, we're finally getting a native way to handle async functionallity in React. Meaning we don't really need to relly on useEffect to fetch our data we can simple create an axios fetch request and wrap it in a use hook.

For example:

export const Post = (id:string) => {
  const fetchPost = axios.get(`/api/posts/${id}`));
  const post = use(fetchPost);
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

This will fetch the post data and render it on the page. No useEffect required or any other async handling library required. 🎉

How does the use hook work

Similary to await it simply unwraps the value of a promise, meaning that any async behaviour can be wrapped in a use hook now and react will natively handle the promise for us.

Do we still need react-query then?

Yes, we do. While the use hook is a great addition to react, it's still not a replacement for react-query. The use hook is only meant to handle async behaviour, not caching or any other advanced features. So if you're looking for a more advanced data fetching library, react-query is still the way to go. However it's a step in the right direction for the react team and a welcome addition to the react ecosystem. I can't wait to see what the community does with this new feature. 🤩

Other interesting stuff of note

Unlike all other hooks the use hook appears to support conditional execution. Much like react-query's enabled option. This means that we can conditionally fetch data based on some condition. This is of course not supported by other hooks and it appears that the use hook is the only hook will support this. A cool future proposal in the RFC is that we can wrap React Context in a use hook as well. Which would allow us to use context in a more declarative way. Not sure if this will make it into the final RFC but it's an interesting idea.

Conclusion

This is by far one of the coolest upcoming features in react. I personally can not wait to use it in my next project. I'm sure we'll see a lot of interesting use cases for this new hook. If you're interested in learning more about the use hook, I highly recommend you check out the RFC. It's a very interesting read and it's a great insight into how the react team thinks about new features.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .