Function withState

  • like useState or you can pass properties to the component to make it controllable

    Type Parameters

    • PropValue

    • StateName extends string

    • SetterName extends string = `set${Capitalize<StateName>}`

    • Props extends object = {}

    Parameters

    • stateName: StateName
    • Optional options: {
          init?: Exclude<PropValue, Function> | ((props) => PropValue);
          setterName?: SetterName;
      }
      • Optional init?: Exclude<PropValue, Function> | ((props) => PropValue)

        the initial value

        Example

        // initial state from a constant
        {init: "initial value"}

        Example

        // initial state will be derived from someProp
        {init: ({ someProp }: {someProp: number}) => someProp + 1}
      • Optional setterName?: SetterName

        the setter's name property, usually you want to the default which is set${Capitalize<StateName>}

        Default

        set${Capitalize<StateName>}

        Example

        withState("someState", {
        init: 0,
        setterName: "setSomeState" // default
        })(Example)

    Returns Hoc<[WithStateFn<PropValue, StateName, SetterName, ToSchema<Props>>]>

    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