首頁 > web前端 > js教程 > 主體

React 新功能 - &#use&# 鉤子

Linda Hamilton
發布: 2024-10-09 14:33:29
原創
765 人瀏覽過

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.

以上是React 新功能 - &#use&# 鉤子的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!