Understanding the future of React
React19 has brought new Hooks to the board to streamline the development process. Here is the breakdown of newly introduced Hooks.
The new use()
hook
React19 will introduce a new hook called use()
. This hook will simplify how we use promises, async code, and context.
Here is the syntax of hook:
import { use } from 'react';
function MessageComponent({ messagePromise }) {
const message = use(messagePromise);
// ...
}
The good news is that this hook can be used for data fetching. Here’s an example of fetching data when the component mounts and when a button is clicked. Note that the useEffect hook is not used in the code:
import * as React from 'react';
import { useState, use, Suspense } from 'react';
import { faker } from '@faker-js/faker';
export const App = () => {
const [newsPromise, setNewsPromise] = useState(() => fetchNews());
const handleUpdate = () => {
fetchNews().then((news) => {
setNewsPromise(Promise.resolve(news));
});
};
return (
<>
<h3>
Here is the news <button onClick={handleUpdate}>Refresh</button>
</h3>
<NewsContainer newsPromise={newsPromise} />
</>
);
};
let news = [...new Array(4)].map(() => faker.lorem.sentence());
const fetchNews = () =>
new Promise<string[]>((resolve) =>
// simulate data fetching with a setTimeout
setTimeout(() => {
// add one more headline at each refresh
news.unshift(faker.lorem.sentence());
resolve(news);
}, 1000)
);
const NewsContainer = ({ newsPromise }) => (
<Suspense fallback={<p>Fetching the news...</p>}>
<News newsPromise={newsPromise} />
</Suspense>
);
const News = ({ newsPromise }) => {
const news = use<string[]>(newsPromise);
return (
<ul>
{news.map((title, index) => (
<li key={index}>{title}</li>
))}
</ul>
);
};
Let’s understand the code:
fetchNews
is responsible for the GET request.- We are using the
use
hook to execute thefetchNews
instead of using theuseEffect
oruseState
hooks. - The return of the
useState
hook isnews
which will have the response of the GET request. - In the return block, we are using
news
to map over it and create the list
Remember this warning in the <Suspense> documentation?
Data fetching with Suspense support without a self-sufficient framework is not supported.
But in React 19, this is no longer relevant.
The use hook has an interesting feature: unlike other React hooks, it can be called inside loops and conditional operators, such as if.
Does this mean that for data fetching on the client side, it is no longer necessary to use third-party libraries, such as TanStack Query? Well, we still have to figure this out, as TanStack Query does much more than just resolving promises.
But this is a step in the right direction, significantly simplifying the creation of single-page applications working with REST or GraphQL APIs. I’m excited about this new hook!