Optional
options: { Optional
init?: Exclude<PropValue, Function> | ((props) => PropValue)the initial value
// initial state from a constant
{init: "initial value"}
// initial state will be derived from someProp
{init: ({ someProp }: {someProp: number}) => someProp + 1}
Optional
setterthe setter's name property, usually you want to the default which is set${Capitalize<StateName>}
set${Capitalize<StateName>}
withState("someState", {
init: 0,
setterName: "setSomeState" // default
})(Example)
const CounterWithState = withState("count", { init: 0 })(function Counter({count, setCount}: {count: number; setCount: Dispatch<SetStateAction<number>>}) {
return <button onClick={() => setCount(count + 1)}>{count}</button>;
});
// using CounterWithState as self controlled
function IndependentCounters() {
return <>
<CounterWithState />
<CounterWithState />
</>;
}
<IndependentCounters /> // will render 2 buttons that can count independently
// using CounterWithState as parent controlled
function SameCounters() {
const [count, setCount] = useState(0);
return <>
<CounterWithState count={count} setCount={setCount} />
<CounterWithState count={count} setCount={setCount} />
</>;
}
<SameCounters /> // will render 2 buttons with the same count
Generated using TypeDoc
like
useState
or you can pass properties to the component to make it controllable