Tip: Label your useState values in React developer tools

React, Hooks · Nov 7, 2021

When working with multiple useState() hooks in React, things can get a bit complicated while debugging. Luckily, there's an easy way to label these values, using the useDebugValue() hook to create a custom useStateWithLabel hook:

const useStateWithLabel = (initialValue, label) => {
  const [value, setValue] = useState(initialValue);
  useDebugValue(`${label}: ${value}`);
  return [value, setValue];
};

const Counter = () => {
  const [value, setValue] = useStateWithLabel(0, 'counter');
  return (
    <p>{value}</p>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <Counter />
);
// Inspecting `Counter` in React developer tools will display:
//  StateWithLabel: "counter: 0"

This hook is obviously meant mainly for development, but it can also be useful when creating React component or hook libraries. Additionally, you can easily abstract it in a way that the label is ignored in production builds. An example would be exporting a hook that defaults back to useState() when building for a production environment.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • Tips & Tricks

    A collection of quick tips and tricks to level up your coding skills one step at a time.

    Collection · 56 snippets

  • Write a useInterval hook in React

    Wrapping your mind around React hooks and how they interact with setInterval() can be difficult. Here's a guide to get you started.

    React, Hooks · Sep 28, 2021

  • Tip: Prefer primitives in useEffect dependencies

    Avoid unnecessary re-runs by using primitive dependencies in your React effect.

    React, Hooks · Jun 12, 2022

  • React useDefault hook

    Creates a stateful value with a default fallback if it's null or undefined, and a function to update it.

    React, Hooks · Oct 23, 2021