DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Dani Akash ๐Ÿงช๐Ÿ’ฅ
Dani Akash ๐Ÿงช๐Ÿ’ฅ

Posted on

Rex State - a handy utility to convert your hooks into shared states

Introducing Rex State v1.0

I initially built rex-state as a state management library, however, since it was using the Context API it wasn't very efficient with handling re-renders.

But then its another feature became more prominent. It can easily convert any hook into a shared state!

Focusing on this functionality, Today I'm releasing Rex State 1.0. This tool is easy to use and will work with your existing hooks.

Usage

Add rex-state to your project

yarn add rex-state

# or

npm i rex-state

Consider you have the following counter hook ๏นฃ

const useCounterHook = (initialCount) => {
  const [count, setCount] = useState(initialCount || 0);

  const increaseCount = () => setCount(count + 1);
  const decreaseCount = () => setCount(count - 1);

  return {
    count,
    increaseCount,
    decreaseCount
  };
};

You can use rex-state to create a provider and a shared hook using the following code ๏นฃ

import { createRexStore } from "rex-state";

const { 
  useStore: useCounter, 
  RexProvider: CountProvider 
} = createRexStore(useCounterHook);

Wrap your application inside the CountProvider ๏นฃ

export default function App() {
  // Starting off with an initial count of 10
  return (
    <CountProvider value={10}>
      <CountDisplay />
      <Controls />
    </CountProvider>
  );
}

Now you can use useCounter hook inside both <CountDisplay/> & <Controls/> components. When the count changes in the <Controls/> component, it will cause the <CountProvider/> to re-render & will also update the <CountDisplay/> component.

This is based on the React.Context API. I have written a detailed page on its performance & when to use it in your application.

Following is a working codesandbox of the counter app ๏นฃ

Read about it detail on Github

Share your thoughts about using this library. I'm open to feedbacks & ideas โœŒ๐Ÿฝ

Top comments (0)

๐ŸŒš Friends don't let friends browse without dark mode.

Sorry, it's true.