DEV Community

CarolinaCobo
CarolinaCobo

Posted on

React Hooks 3: New Hooks in React 18

I’m still familiarising myself with the new updates in React 18 such as Concurrency, Automatic Batching, and the new Transitions and Suspense features (I might write about it). Still, to finish this section I’m going to go over the new Hooks in React 18.

useId

This new Hook will generate a unique ID on both sides, client and server while avoiding hydration mismatches.

This Hook will be useful mostly in component libraries that are integrated with Accessibility APIs that require unique IDs.

Remember: useId is not for generating keys in a list, the keys should be generated from your data.

For a basic example, pass the id directly to the elements that need it:

function Checkbox() {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>This is an Example</label>
      <input id={id} type="checkbox" name="react"/>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

For multiple IDs in the same component, append a suffix using the same id:

function NameFields() {
  const id = useId();
  return (
    <div>
      <label htmlFor={id + '-firstName'}>First Name</label>
      <div>
        <input id={id + '-firstName'} type="text" />
      </div>
      <label htmlFor={id + '-lastName'}>Last Name</label>
      <div>
        <input id={id + '-lastName'} type="text" />
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

useTransition and startTransition

They will allow you to mark some state updates as not urgent, some updates might be considered urgent by default (updating a text input) and these ones will be allowed to interrupt the non-urgent ones.

const [isPending, startTransition] = useTransition();
//startTransition lets you mark updates in the provided callback as transitions:
startTransition(() => {
  setCount(count + 1);
})
//isPending indicates when a transition is active to show a pending state:
function App() {
  const [isPending, startTransition] = useTransition();
  const [count, setCount] = useState(0);

  function handleClick() {
    startTransition(() => {
      setCount(c => c + 1);
    })
  }

  return (
    <div>
      {isPending && <Spinner />}
      <button onClick={handleClick}>{count}</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

useDeferredValue

Accepts a value and returns a new copy of the value that will defer to more urgent updates. In case the current render is the result of an urgent update, such as user input, React will return the previous value and then render the new value after the urgent render has been completed.

This one is similar to user-space hooks which use debouncing or throttling to defer updates. The benefits of using it are that React will work on the update as soon as other work finishes (instead of waiting for an arbitrary amount of time), and deferred values can be suspended without triggering an unexpected fallback for existing content.

It also only defers the value that you pass to it. In case you want to prevent a child component from re-rendering during an urgent update, you must also memoize that component with React Memo or React useMemo

function Typeahead() {
  const query = useSearchQuery('');
  const deferredQuery = useDeferredValue(query);

  // Memoizing tells React to only re-render when deferredQuery changes,
  // not when query changes.
  const suggestions = useMemo(() =>
    <SearchSuggestions query={deferredQuery} />,
    [deferredQuery]
  );

  return (
    <>
      <SearchInput query={query} />
      <Suspense fallback="Loading results...">
        {suggestions}
      </Suspense>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

useInsertionEffect (intended to be used in Libraries,)

useInsertionEffect is a new hook that allows CSS-in-JS libraries to address performance issues of injecting styles in render. Unless you’ve already built a CSS-in-JS library it’s not likely you’ll ever use this.

As the source of all this information and or further reference, you should review the React Hooks Documentation.


Thanks for reading, I appreciate your time. If you need any help or have any questions please reach out!

If you have any questions feel free to drop me a message on LinkedIn or send me an email. 😊

Have a nice day!

Top comments (0)