Skip to content

A `useState` hook that can accept class instance as state.

License

Notifications You must be signed in to change notification settings

pilagod/use-cls-state

Repository files navigation

use-cls-state Build Status Coverage Status

A useState hook that can accept class instance as state.

Installation

npm install --save use-cls-state

Usage

useClsState is just like useState, with additional capability to accept class instance as state.

import { useClsState } from "use-cls-state";

class State {
  public constructor(public counter: number) {}

  public increment() {
    this.counter = this.counter + 1;
  }
}

function Page() {
  const [state, setState] = useClsState(new State(123));
  const increment = () => {
    // Update class instance will not trigger re-render
    state.increment();
    // Re-render is only triggered when calling state setter
    setState(state);
  };
  return (
    <div>
      <p>{state.counter}</p>
      <button onClick={() => increment()}>Increment</button>
    </div>
  );
}

Be aware when using class instance as state, updating properties on the class instance will NOT trigger re-render. Re-render is only triggered when calling state setter.

License

© Cyan Ho (pilagod), 2024-NOW.

Released under the MIT License.

About

A `useState` hook that can accept class instance as state.

Resources

License

Stars

Watchers

Forks

Packages

No packages published