DEV Community

Aung Myat Moe
Aung Myat Moe

Posted on

1

The way we store state globally in react

Oden Reactive Store

To leverage the power of reactive programming, we need to be able to store data in a reactive way.
This lib provides a simple way to define a reactive store for your micro-frontend application.

Installation

npm i oden-reactive-store
Enter fullscreen mode Exit fullscreen mode

Usage

Define a store which will global accessible and reactive in your application which means when you change state in
another
component it will be updated in all other components which are using the same store.

import {defineStore} from "oden-reactive-store";

export const useCounterStore = defineStore(0)
Enter fullscreen mode Exit fullscreen mode

Now you can use the store in your components like this.
You can use the store via custom hook useCounterStore which will return the current state and a function to update the
state like useState.

import {useCounterStore} from "../store/useCounterStore";

const Counter = () => {
    const [count, setCount] = useCounterStore();

    return (
        <div className="card">
            <button onClick={() => setCount((count) => count + 1)}>
                count is {count}
            </button>
        </div>
    );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

And you can use your component like this.
When you click the counter button it will be updated in all other components which are using the same store.

function App() {

    return (
        <div className="App">
            <h1>Reactive Store</h1>
            <Counter/>
            <Counter/>
            <div>
                Counter value will change across all components due to reactive store behavior
            </div>
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay