Skip to main content

Command Palette

Search for a command to run...

5 React hooks that you should know

A quick info about 5 react hooks

Updated
3 min read
5 React hooks that you should know
  1. useId:

    useId is one of the simplest hooks in react and it is used to generate unique id’s for related elements on both client and server side. It can be passed to accessibility attributes

import { useId } from 'react';

function InputField() {
  const id = useId();
  return (
    <div>
      <label htmlFor={id}>Name:</label>
      <input id={id} type="text" />
    </div>
  );
}
  1. useDeferredValue:

    Often times addressing sluggish rendering is a key goal. When rendering a component multiple times for a large number of inputs, it leads to delays and slower render times. So this hook introduces a delay in updating the hook value, that is it lets you defer updating a part of the UI, enhancing user experience by preventing immediate rendering and allowing a smoother display of character as user types

import { useState, useDeferredValue } from 'react';

function Search({ items }) {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);

  const filteredItems = items.filter(item =>
    item.includes(deferredQuery)
  );

  return (
    <>
      <input value={query} onChange={e => setQuery(e.target.value)} />
      <ul>
        {filteredItems.map(item => <li key={item}>{item}</li>)}
      </ul>
    </>
  );
}
  1. useTransition

    This hooks also addresses performance concerns like the useDeferredValue, by rendering a part of the UI in the background.

How to use useTransition:

The useTransition hook returns an array containing two elements:

  • isPending:

    A boolean value that indicates whether a transition is currently in progress. This can be used to display a loading indicator or other visual feedback to the user.

  • startTransition:

    A function that takes a callback as an argument. Any state updates wrapped within this callback will be treated as a "transition," meaning they are marked as non-urgent and can be interrupted by more urgent updates.

      import { useState, useTransition } from 'react';
    
      function Search() {
        const [query, setQuery] = useState('');
        const [isPending, startTransition] = useTransition();
    
        const handleChange = (e) => {
          const nextQuery = e.target.value;
          setQuery(nextQuery);
          startTransition(() => {
            // Non-urgent state updates go here
          });
        };
    
        return (
          <>
            <input value={query} onChange={handleChange} />
            {isPending && <span>Loading...</span>}
          </>
        );
      }
    
    1. useSyncExternalStore

This hooks comes into play when react states are managed by third party libraries or browser APIs like Redux or localStorage. This hook allows subscriptions to these external states, ensuring components re-render upon changes in the external store

  •     import { useSyncExternalStore } from 'react';
    
        // Simple external store
        const store = {
          state: { count: 0 },
          listeners: new Set(),
          increment() {
            this.state.count += 1;
            this.listeners.forEach((listener) => listener());
          },
          subscribe(listener) {
            this.listeners.add(listener);
            return () => this.listeners.delete(listener);
          },
          getSnapshot() {
            return this.state.count;
          }
        };
    
        function Counter() {
          const count = useSyncExternalStore(
            store.subscribe,
            store.getSnapshot
          );
    
          return (
            <div>
              <p>Count: {count}</p>
              <button onClick={() => store.increment()}>Increment</button>
            </div>
          );
        }
    
  1. useInsertionEffect

    While useEffect executes a function after component rendering, the useInsertionEffect is designed for inserting elements into the DOM before layout effects fire, like dynamic styles, without server rendering.

     import { useInsertionEffect } from 'react';
    
     function DynamicStyle({ color }) {
       useInsertionEffect(() => {
         const style = document.createElement('style');
         style.textContent = `.dynamic-box { background-color: ${color}; }`;
         document.head.appendChild(style);
    
         return () => {
           document.head.removeChild(style);
         };
       }, [color]);
    
       return <div className="dynamic-box">I change color dynamically!</div>;
     }