I want to React.use() this!
I want to React.use() this!
By Dave Bitter
4 min read
A big part of working with React.js is fetching data and displaying the results. Let’s see how the new React.use() hook can can help you!
- Authors
- Name
- Dave Bitter
- linkedinDave Bitter
- twitter@dave_bitter
- Github
- githubDaveBitter
- Website
- websiteBlog
There’s quite a bit of chatter lately about an experimental hook called React.use()
. This will fundamentally change the way you work with React.js. Let’s have a look at what it is, why you would want to React.use()
it and how it works!
React.use()
?
What is React.use()
is an experimental hook that offers first-class support for promises and async/await. In essence, it means that you can await asynchronous code in the root of your components.
Couldn’t you already do that? Nope! Sure you could have promises in React.js for, for instance, data fetching, but you always used something like useEffect
for this. The component, or rather function that returns some JSX, always just ran. There was no way to pause it to await some asynchronous code. Until now.
React.use()
this?
Why would I want to The ability to now await some asynchronous code will for instance have a big impact on how you load data into your component. Previously, you would have to resort to useEffect
to fetch data. You would then have to add some state where you store the data and potentially show a spinner while the data is being fetched. This could look something like this:
import React, { useEffect, useState } from 'react'
const YourComponent = () => {
const [isLoading, setIsLoading] = useState(false)
const [data, setData] = useState([])
useEffect(() => {
setIsLoading(true)
fetch('api.com/data')
.then((res) => res.json())
.then((result) => {
setData(result)
setIsLoading(false)
})
}, [])
if (isLoading) {
return 'Loading...'
}
if (!data) {
return 'No data'
}
return (
<ul>
{data.map((datum) => (
<li key={datum.id}>{datum.name}</li>
))}
</ul>
)
}
export default YourComponent
Note that all the data fetching happens on the client-side. Because of this, the first time the component renders on the client you start fetching data and you need to show some feedback to the user. In this simplified example that is the string ‘Loading…’, but more than likely you display a spinner.
This isn’t great as the component is rather useless if the data is not fetched yet. So, even though you might have server-side rendering, you won’t really get any benefits. You have to do it this way as you couldn’t run the fetching logic on the server before due to the need of useEffect
. As the JavaScript function (or often named “component”) is just a function that will run on the server, why can’t I pause that function, fetch the data on the server and then have the first render already use that fetched data on the server? This is why you want React.use()
.
React.use()
it?
How do I You can simply import the use
hook from the React.js package. Next, you pass it a fetching function, or rather, a Promise. Finally, you assign the response to a variable. The updated example would look a bit like this:
import React, { use } from 'react'
const getData = fetch('api.com/data').then((res) => res.json())
const YourComponent = () => {
const data = use(getData)
if (!data) {
return 'No data'
}
return (
<ul>
{data.map((datum) => (
<li key={datum.id}>{datum.name}</li>
))}
</ul>
)
}
export default YourComponent
It looks like a minor change, but let’s see what you gained.
Firstly, you got rid of the useEffect
and useState
hooks. Even better, you got rid of any client-side code! This is now a server component which, when server-side rendering, the function will pause on the server, fetch some data and then return the “filled JSX”.
Secondly, you simplified the logic. As you don’t need the before-mentioned hooks and callbacks, the code is drastically simplified. Now, this is a simple demo component, but you can imagine more complex components really benefitting from this.
Finally, you could remove any of the loading state. Because of the use
hook waited on, the rest of the code will never be executed before it’s done. Of course, you still have to handle the state where there's no data returned from the endpoint, but you can forget about any loading feedback.
useEffect
hook?
So, no more data fetching in the Not necessarily, you now have two options which both have their benefits. use
is great to fetch the data on the server when the component isn’t very useful without the data. Fetching data in a useEffect
hook is useful when you do want to show the UI while it is fetching the data.
Closing thoughts
I’m very excited for React.use()
and the move to server side-first. With frameworks like Remix and Next.js creating solutions for this problem, it’s good to see a standard coming to React.js that can be utilised by both. It will drastically simplify data fetching and help you create robust server-first components!
Upcoming events
Drupal CMS Launch Party
Zoals sommigen misschien weten wordt op 15 Januari een nieuwe distributie van Drupal gelanceerd. Namelijk Drupal CMS (ook wel bekend als Starshot). Om dit te vieren gaan we op onze campus een klein eventje organiseren. We gaan die dag samen de livestream volgen waarbij het product gelanceerd wordt. De agenda is als volgt: 17u – 18u30: Drupal CMS livestream met taart 18u30 – 19u00: Versteld staan van de functionaliteiten 19u – 20u: Pizza eten en verder versteld staan van de functionaliteiten Laat ons zeker weten of je komt of niet door de invite te accepteren! Tot dan!
| Coven of Wisdom Herentals
Go to page for Drupal CMS Launch PartyCoven of Wisdom - Herentals - Winter `24 edition
Worstelen jij en je team met het bouwen van schaalbare digitale ecosystemen of zit je vast in een props hell met React of in een ander framework? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en flexibele applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Building a Mature Digital Ecosystem - Maarten Heip 20:00 – 🍹 Kleine pauze 20:15 – 📢 Compound Components: A Better Way to Build React Components - Sead Memic 21:00 – 🙋♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op het bouwen van digitale ecosystemen en het creëren van herbruikbare React componenten. Maarten deelt zijn expertise over het ontwikkelen van een volwassen digitale infrastructuur, terwijl Sead je laat zien hoe je 'From Props Hell to Component Heaven' kunt gaan door het gebruik van Compound Components. Ze delen praktische inzichten die je direct kunt toepassen in je eigen projecten. 📍 Waar? Je vindt ons bij iO Herentals - Zavelheide 15, Herentals. Volg bij aankomst de borden 'meetup' vanaf de receptie. 🎫 Schrijf je in! De plaatsen zijn beperkt, dus RSVP is noodzakelijk. Dit helpt ons ook om de juiste hoeveelheid eten en drinken te voorzien - we willen natuurlijk niet dat iemand met een lege maag naar huis gaat! 😋 Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.
| Coven of Wisdom Herentals
Go to page for Coven of Wisdom - Herentals - Winter `24 editionThe Test Automation Meetup
PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🍻 Drinks 21:00 – 🙋♀️ See you next time? First Round of Talks: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Overcoming challenges in Visual Regression Testing - Sander van Surksum, Pagespeed | Web Performance Consultant and Sannie Kwakman, Freelance Full-stack Developer How can you overcome the challenges when setting up Visual Regression Testing? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!
| Coven of Wisdom - Amsterdam
Go to page for The Test Automation Meetup