DEV Community

Abdulrahman Ismael
Abdulrahman Ismael

Posted on

Unlocking the Power of React: Fresh Hooks to Expand Your Development Toolkit

React hooks


React has introduced some new hooks that can make it easier to use React.
We're going to discuss some of them today. Enjoy 😉


1. useId:

  • useId is a new release hook in React. It is used to generate unique IDs.
  • It can help in many matters, especially with accessibility attributes in HTML Elements.
  • Do not try to use useId to generate keys in a list. Keys should be generated from the data itself.
import { useId } from 'react';

function generateUniqueKey() {
  const uniqueKey = useId();
  .
  .
}
Enter fullscreen mode Exit fullscreen mode

2. useTransition:

  • You may want to update the state of useState hook without changing the UI, now you can do that using useTransition.
  • In other words, useTransition is used to mark some states as non-blocking transitions. which means updating states won't block the UI as if nothing changed and that might be useful in some situations.
  • useTransition accepts no parameters. But it returns 2 things:
  1. Ispending: which indicates whether there is a transition or not
  2. transitionFn: function that is used to mark states as transitions by calling the set functions within its function parameter.
function CountComponent() {
  const [isPending, transitionFn] = useTransition();
  const [count, setCount] = useState(0);

  function markCountAsTransition(nextCount) {
    transitionFn(() => {
      setCount(nextCount);
    });
  }
  .
  .
}
Enter fullscreen mode Exit fullscreen mode

3. useDeferredValue

  • useDeferredValue is used to delay showing the new value of state or prop in the UI when you change it.
  • So, when you change the state, the UI still uses the old value, and the new value is updated in the background. Then, after any other re-renders happen, the UI will use the new value.
  • It accepts state or prop that is displayed in the UI as a parameter and returns the deferred value, so make sure to use the deferred value instead of the original one to delay the display.
import { useState, useDeferredValue } from 'react';

function DeferValue() {
  const [state, setState] = useState(0);
  const deferredState = useDeferredValue(state);
  .
  .
  .

  return <div> {deferredState} </div>
}
Enter fullscreen mode Exit fullscreen mode

These are some of the new introduced hooks, and they're the most significant ones for now. In the future, this article might be updated with any new hooks that are released.
I hope you enjoyed and unleashed your knowledge today 😃

Have a nice day 🌹

Top comments (0)