Reputation:
I want to pass a state and it's setState function together as a single property. Is that possible? Right now I have to do like: state={state} setState={setState} and it's kind of messy
Upvotes: 0
Views: 35
Reputation: 83527
One option is to create an object:
state={{
state,
setState,
}}
Upvotes: 1
Reputation: 370659
You could continue to use the array returned by useState
:
const stateContainer = useState('foo');
// ...
return <SomeComponent {...{stateContainer}} />
And then in SomeComponent
, extract the state and setter from the container.
const [state, setState] = stateContainer;
If you have to use the state and setter in the parent component too, you might want to continue destructuring the useState
call, in which case shorthand property names are another option:
return <SomeComponent {...{state, setState}} />
Upvotes: 4