New React 18 Hooks

What is the new React 18 Hooks

React team has released React 18 and the theme for this release is concurrency. Needless to say, React 18 has introduced some new hooks to help us build better and more responsive web applications:

  1. useTransition
  2. useDeferredValue
  3. useId

Today, we will take a look at how to use these hooks in your project in practice.

useTransition Hook

By default, all state updates are equally important. They will share the resources for any computation and refreshing the screen. By using useTransition hook, you can tell React which updates are urgent and which are not.

Urgent updates: The updates that need to provide immediate feedback to the user to provide the best user experience, such as button click, text input, etc.

Transition updates: The changes in the display that users may expect a slight delay include refreshing the result based on filter, changes in content, etc.

Let’s take a look at the example below of filtering the list, in which we allow the user to input a search term and filter the list based on the search term.

You will find that the input that used useTransition hook is much more responsive compared to the one without.

In addition, you can also use startTransition method if hooks are not available.

import { startTransition } from 'react';

startTransition(() => {
  // Do something
});

useDeferredValue hook

This hook is self-explanatory as it will defer value changes for other urgent updates. It is similar to debouncing but without a fixed time delay. React will render the deferred updates immediately after the essential updates are finished.

Again, we will use the filter list example, but we will be using useDeferredValue hook instead of useTransition hook.

Similarly, you will find that the input with deferred value will be more responsive than the other. However, useDeferredValue does not provide the isPending flag for us to show the visual feedback to the user.

You will also need to memoize the children’s components that used the deferred value to prevent re-rendering because of the urgent updates.

useId hook

useId helps to generate a globally unique id across the application. It is consistent across servers and clients to avoid hydration mismatches.

Nevertheless, the useId hook must not use this hook for generating keys in the list.

Conclusion

The React team has released React 18 for a while. You can try to think about how you can leverage these hooks on your project.

Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top