score:5

Accepted answer

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] = usestate({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

score:3

you can use usedebugstate hook from use-named-state package.

import { usedebugstate } from "use-named-state";
const app = () => {
  const [counter, setcounter] = usedebugstate("counter", 0);

  return <button onclick={(prevcount) => prevcount + 1}>{counter}</button>;
};

it internally uses usedebugvalue hook from react (method suggested by @venryx)

score:5

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.

score:26

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.

  1. create a new usestatewithlabel function:
function usestatewithlabel(initialvalue, name) {
    const [value, setvalue] = usestate(initialvalue);
    usedebugvalue(`${name}: ${json.stringify(value)}`);
    return [value, setvalue];
}

it's based on the usedebugvalue function described here.

usage:

const [item, setitem] = usestatewithlabel(2, "item");

score:28

finally react team listened to us

the recent introduction of parsing custom hooks in react dev tools option might help
.

before parsing ( before clicking the magic button in custom hooks card )

enter image description here

. enter image description here .

after parsing ( clicking the magic button in the top right )

enter image description here


Related Query

More Query from same tag