score:5
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:
- 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.
- 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
Source: stackoverflow.com
Related Query
- Is there any way to see names of 'fields' in React multiple state with React DevTools when using 'useState' hooks
- Is there a generic way to set state in React Hooks? How to manage multiple states?
- Is there such a thing as a "correct" way of defining state with React hooks and Typescript?
- any way to have multiple tabs(screens) in react native with a preview like in a browsers do for example?
- React error: warn There are multiple modules with names that only differ in casing
- Is there any way to crop videos in JavaScript with a crop box, without using React or Vue?
- Is there any function to use to see the new updated array state using React Js Hook?
- Is there a way in React to save something in state without using any hooks?
- Is there any way to block user navigation with out any prompt in react
- Is there any way to define the datatype of value in state of hooks in functional component of react JS?
- React Leaflet: Is there a way to make an onClick method that adds a marker and also updates the state with that markers' location? (Beginner React)
- Is there any way to change state inside render in React js?
- Is there any differences in react hook with set multiple states?
- Correct way to update state with react select multiple
- Is there any way to store the files locally on computer using react with electron
- Is there a way in React to execute only part of the render function multiple times, while the other part keeps going with initial execution?
- Is there a way to use react multiple select with this
- Is there any way to send multipart form request to graphql in reactjs with react relay modern
- Is there a way to render multiple React components in the React.render() function?
- Is there any proper way to integrate d3.js graphics into Facebook React application?
- Is there any way to access the current locale with React-Intl?
- React state with calculated fields
- is there any way to disable or speed up React PropType validation in development mode?
- Is there a way to apply a fade in/out transition with React suspense for the fallback component?
- Any way for React in a popup to communicate with parent window?
- Is there any way to detect middle click in React JS?
- Is there any way to avoid "Text content did not match" warning in SSR with React?
- Set multiple state values with React useState hook
- I have built a global state redux like pattern with context and hooks. Is there a way to combine reducers?
- Is there any way to make React Material-UI radio buttons required
More Query from same tag
- HTML BootStrap Navbar not displaying as expected
- Handle click event when button inside cell is pressed
- Where do I handle form validation errors returned by the server in my React app?
- create-react-app sample app problems
- Importing a directory in React
- How to update only if my object has a certain field
- How to toggle CSS class between buttons rendered with .map()
- Getting error when using type "React.ReactNode" to children. Which type should I use?
- How to correctly wait for fetch in a react class
- Collapsible list with a loadmore button to show all the items from this list
- How to navigate within page in react?
- Conditional rendering on React.js
- How to include s3image inside ReactJs card
- Insert a div that does not exist in html form sass/css
- Relay Pagination: How to initialize "after" value?
- Best way to pass in a React component?
- ThunkAction getting returned by dispatch instead of the Return Type of the ThunkAction
- Redux Thunk Action Creator Not Getting Called
- How to display true for a certain range of digits?
- React, error when generating tabs dynamically
- Render JSX elements within a function
- Om but in javascript
- JS filter or find an element in array where owner_name matches in react
- Hacking authentication usind react-dev-tools
- Can we add properties to immutable object in JavaScript?
- React doesn't display initial state of UI on start
- React persistent login with JWT
- Setting background image to full screen React
- Stripe /v1/payment_intents/:id/confirm returns HTTP 400 “Received unknown parameters” (Stripe Elements and React)
- useEffect cleanup on 'imported' async function