Is there any way to see names of 'fields' in React multiple state with React DevTools when using 'useState' hooks
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");
You are not missing anything and you can't change this behaviour. This is how React deals with multiple state.
https://reactjs.org/docs/hooks-rules.html#explanation.
One way to avoid this problem is to use a single State Hook which creates a single state including all the data.
const [state, setState] = useSate({doughnuts: 24, key1: 'value1', key2: 'value2'});
In this case the state is stored in a single object and each value is associated with a key.
Take a look at this: Should I use one or many state variables?
A compound state is hard to manage, but there is a tool which can help you with that: useReducer Hook
When you do the following operation
const [item, setItem] = useSate(2)
You're using destructuring assignment
in an array
a type which does not contain a key
like an object
. You're just creating an alias
to access the first element of the array returned by useState
. If you do something like this
const [item, setItem] = useState({value: 2})
You will be able to see value: 2
in your dev-tools, cause it reflects the current state of that hook at a certain point of time.
Each time you call a Hook, it gets isolated local state within the currently executing component based on the previous value, so the identifier attributed by you (item
) will only be scoped to that render cycle, but it doesn't mean that React
reference is using the same identifier.