user15615257
user15615257

Reputation:

Passing state and setstate together in React

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

Answers (2)

Code-Apprentice
Code-Apprentice

Reputation: 83527

One option is to create an object:

state={{
    state,
    setState,
}}

Upvotes: 1

CertainPerformance
CertainPerformance

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

Related Questions