Simplifying State Management in Microfrontends with Jotai
Jotai, a lightweight and super-easy state management library that’s perfect for microfrontends.
Why is it used?
It’s simple, minimal, and works well for both small and complex apps—perfect for microfrontends!
Why Use Jotai in Microfrontends?
In microfrontends, sharing state across multiple apps can be a pain! Jotai makes it easy because:
Quick Example: Using Jotai in Microfrontends
Let’s say we have two microfrontends:
Here’s how you can share state using Jotai:
Step 1: Create a Jotai Store (Shared Atom)
Create an atoms.ts file in a shared package:
import { atom } from 'jotai';
// Atom to store cart items
export const cartAtom = atom<string[]>([]); // Array of product names
Recommended by LinkedIn
Step 2: Use the Atom in Microfrontends
1. Product List Microfrontend: Add items to the cart
import React from 'react';
import { useAtom } from 'jotai';
import { cartAtom } from './atoms'; // Import the shared atom
export default function ProductList() {
const [cart, setCart] = useAtom(cartAtom);
const addToCart = (product: string) => {
setCart([...cart, product]); // Update the cart
};
return (
<div>
<h2>Product List</h2>
<button onClick={() => addToCart('Product A')}>Add Product A</button>
<button onClick={() => addToCart('Product B')}>Add Product B</button>
</div>
);
}
2. Cart Microfrontend: Display the cart
import React from 'react';
import { useAtom } from 'jotai';
import { cartAtom } from './atoms'; // Import the shared atom
export default function Cart() {
const [cart] = useAtom(cartAtom);
return (
<div>
<h2>Cart</h2>
{cart.length > 0 ? (
<ul>
{cart.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
) : (
<p>Your cart is empty!</p>
)}
</div>
);
}
Step 3: Host the Shared Atom
You can host the atoms.ts file in a shared package or a microfrontend-specific library (e.g., @shared/store) and import it into both microfrontends.
How Jotai works well in microfrontends?
Final Thoughts
Jotai is a perfect match for microfrontends. It’s simple, fast, and easy to integrate. If you’re building microfrontends and struggling with state sharing, give Jotai a try—it’s a game-changer!