1.6.0 • Published 6 months ago

react-generic-state-hooks v1.6.0

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

react-generic-state-hooks

Generic State Hooks for React

About the library

react-generic-state-hooks has been created to provide a simple way for creating reusable data sources ready for use anywhere in the application. The library allows you to define hooks for reading and modifying the same data, regardless of where it is used.

Docs, tutorials and examples can be found here.

Quick guide

Installation

npm install react-generic-state-hooks

Basic usage:

// inMemoryStateHooks.ts
import { createInMemoryStateHooks } from 'react-generic-state-hooks';

export const { useValue, useList, useRecord
} = createInMemoryStateHooks('my-namespace');

Now, you can use generic hooks in any place of your application:

// MyComponent.tsx
import { useValue } from './inMemoryStateHooks';

const MyComponent = () => {
  const [value, setValue] = useValue('counter', 0);
  return (
    <>
      <div>count: {value}</div>
      <button onClick={() => setValue(value + 1)}>click me</button>
    </>
  );
}

Creating Custom Hooks

If you plan to use the same data in multiple places in the application, a better approach would be to create a dedicated hooks based on generic hooks:

// useCounter.ts
import { useValue } from './inMemoryStateHooks';
export const useCounter = () => useValue('counter', 0);

Just like generic hooks, you can use them in any place of your application:

// MyComponent.tsx
import { useCounter } from './useCounter';

const MyComponent = () => {
  const [value, setValue] = useCounter();
  return (
    <>
      <div>count: {value}</div>
      <button onClick={() => setValue(value + 1)}>click me</button>
    </>
  );
}
Click here for full documentation
1.6.0

6 months ago

1.5.0

6 months ago

1.4.0

6 months ago

1.3.1

6 months ago

1.3.0

6 months ago

1.2.0

6 months ago

1.1.0

6 months ago

1.0.0

6 months ago