I've been learning/experimenting with React hooks. When I go to inspect the values of the current state of a component using React DevTools in Chrome, I see the state fine, but the actual 'fields' -- that is, the state variables that are being updated by the individual useState
hooks -- don't have any name associated with them. Instead, I see, for example, several strings, a couple of booleans, etc. I can generally figure out what's going on, but this seems problematic -- I'd like to be able to see which what the state variable's name is.
For instance, if I have something like
const [doughnuts, setDoughnuts] = useState(24)
When I look in React DevTools I'd like to see something like `doughnuts: number : 24', instead of just 'number: 24'.
Am I missing some setting somewhere, or some technique to turn on this ability?
By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you're curious, we'll explain this in depth below.)
Access React components and state from the console Select a component in React DevTools and pop open the console (hitting the Esc key lets you see both at once). Type in $r and you'll have access to the instance of that React component from the console.
Open the console by either right-clicking and inspecting an element or by opening the toolbar by clicking View > Developer > JavaScript console. The Components tab will show the current React component tree, along with any props, state, or context.
React Developer Tools is a Chrome DevTools extension for the open-source React JavaScript library. It allows you to inspect the React component hierarchies in the Chrome Developer Tools. You will get two new tabs in your Chrome DevTools: "⚛️ Components" and "⚛️ Profiler".
Some approaches not mentioned in the other answers:
1) Use the following:(suggested by Oleh)
const [{ item }, setItem] = useState({ item: 2 });
You could also wrap the useState
function so that, based on the shape of the initial value, the setItem
function it returns auto-converts from the passed value itself into an object with the correct (wrapper) shape.
2) Create a new useStateWithLabel
function:
function useStateWithLabel(initialValue, name) { const [value, setValue] = useState(initialValue); useDebugValue(`${name}: ${value}`); return [value, setValue]; }
It's based on the useDebugValue
function described here.
Usage:
const [item, setItem] = useStateWithLabel(2, "item");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With