Skip to content

Using with other libraries

Genshi is written in TypeScript and can be used with any JavaScript framework or library.

If you are using a library that is not officially supported, you can still use Genshi with it. You will have to create your library-specific bindings to work with the library.

Installation

To use Genshi with other libraries, you need to install the core package using your favorite package manager.

Terminal window
npm i @genshi/core

Usage

Genshi provides a Store class that you can use to create a store for your application. Everything you need to manage your application state is provided by the Store class.

Creating our store

First, let’s create a store with an initial state.

import { Store } from "@genshi/core";
const store = new Store({
count: 0,
});

The Store class creates an instance of the store. It also provides methods to define and dispatch actions and effects.

Defining actions

The action method on the store instance is used to define an action. The action function takes the current state as an argument and returns the new state.

const increment = store.action("increment", (state) => ({
...state,
count: state.count + 1,
}));

The above action increments the count by 1.

Defining effects

The effect method on the store instance is used to define an effect. The effect function provides many properties to ease managing effects. One such property is the dispatch method, which can be used to dispatch other effects or actions.

const tick = store.effect("tick", ({ dispatch }) => {
setInterval(() => {
dispatch(increment);
}, 1000);
});

The above effect dispatches the increment action every second.

Using the store in your application

Now that we have defined our actions and effects, we can use the store in our application.

In this case, we will consider a simple counter application built in React, that uses the @genshi/core package directly.

function Counter() {
const [count, setCount] = useState(store.getState().count);
useEffect(() => {
const listener = store.subscribe((state) => {
setCount(state.count);
});
return listener.remove;
}, []);
useEffect(() => {
store.dispatch(tick);
}, []);
const handleIncrement = () => {
store.dispatch(increment);
};
return (
<>
<button onClick={handleIncrement}>Increment</button>
<p>The count is: {count}</p>
</>
);
}