Home >Web Front-end >JS Tutorial >React new features - the &#use&# hook

React new features - the &#use&# hook

Linda Hamilton
Linda HamiltonOriginal
2024-10-09 14:33:29842browse

React new features - the

React 19 (RC version—as of September 2024) is the latest release of the popular web development library.
V19 is a significant milestone, bringing many new features and hooks. This post will discuss one of these hooks, the use hook.

The use hook

This hook allows developers to suspend the rendering of a UI component until an asynchronous task, such as fetching data or loading resources, is completed by suspending the received promise, without the need for complex state management.

Fetching data example

We have a simple component that uses the classic approach, the useEffect hook, and fetches data from a mock API (I'm using MSW).
We manage a local state for storing the data, along with isLoading and isError fetch states:

const [users, setUsers] = useState<any>(null);
const [isError, setIsError] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState<boolean>(true);

When the page first loads, we run this useEffect hook to fetch the data, store it, and update the various states:

const fetchData = async () => {
  const response = await fetch('/api/users');
  return response.json();
};


useEffect(() => {
  fetchData()
    .then(setUsers)
    .catch(() => setIsError(true))
    .finally(() => setIsLoading(false));
}, []);

We show some UI while the request is being processed or if we encounter an error:

if (isLoading) {
  return <h2>Loading...</h2>;
}
if (isError) {
  return <h2>Error</h2>;
}

and finally! We render the users list:

return ( 
  <>
    {users.map((user) => {
      return (
        <div>
          {user.lastName}, {user.firstName}
        </div>
      );
    })}
  </>
);

A lot of boilerplate code!

Now, let’s refactor!

Let’s remove the useState and useEffect hooks. We will keep the fetchData method as it is.
Now we will fetch the data using the new use hook, which takes a promise and returns either JSON data or an error:

const users = use(fetchData());

The way this hook works is similar to doing something like this:

const users = await fetchData();

Handling isLoading and isError

To handle these state changes, we’ll go to our App component. We’ll use the React Suspense component, which is designed to respond to asynchronous events. It displays a fallback UI until its children have finished loading.

For error handling when working with Suspense, it’s common practice to use an ErrorBoundary. We’ll add an ErrorBoundary component that implements React’s getDerivedStateFromError() method.

<ErrorBoundary fallback={<h2>Error</h2>}>
  <Suspense fallback={<h2>Loading...</h2>}>
    <UserList />
  </Suspense>
</ErrorBoundary>

Some extra’s

The usual rules for hooks do not apply here — you can use this hook anywhere you'd like!

Unlike regular hooks, the use hook can be used conditionally with an if statement, allowing you to decide whether to trigger it or not. For example, if you want to wrap a new API request with a feature flag and toggle it for testing, simply pass the feature flag to the UserList component and wrap the use hook. It's that simple!

Now, modify the App component:

<ErrorBoundary fallback={<h2>Error</h2>}>
  <Suspense fallback={<h2>Loading...</h2>}>
    <UserList testNewApi={true} />
  </Suspense>
</ErrorBoundary>

Modify the UserList component:

let users = [];
if(testNewApi){
  user = use(fetchData());
}

You can also use this hook to obtain a Context object, rather than using the regular method:

const data = useContext(myContext);

You can use the use hook here, for example, if you want to retrieve the context based on a conditional statement.

Conclusion

In this article, I've outlined the syntax of the use hook and provided usage examples. This should help you grasp these hooks and how to implement them effectively. I hope you find this information beneficial for your future projects.

The above is the detailed content of React new features - the &#use&# hook. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn