iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👻

Jotai isn't just for React, so you can even blink an LED

に公開
2025/07/12

The title is a lie. It is related to React.

However, the parts independent of React are separated as jotai/vanilla, so it can be used without React.
This feature not only allows it to be used in other frontends like Vue besides React, but also makes it useful in unit tests and server-side environments.

Code for blinking an LED on Raspberry Pi

I wrote the following code (partial excerpt).
https://github.com/mitayuki3/node-led-blinker-example/tree/main/jotai

import { atom, createStore } from "jotai/vanilla";

let led;
let blinkInterval = null;

const lampAtom = atom(false);
const toggleAtom = atom(null, (get, set) => {
  const prev = get(lampAtom);
  set(lampAtom, !prev);
});
const store = createStore();

// Monitor the value of lampAtom and reflect it in the LED output
store.sub(lampAtom, () => {
  const value = store.get(lampAtom);
  if (value) {
    led.on();
    console.log("LED: turn ON");
  } else {
    led.off();
    console.log("LED: turn OFF");
  }
});

async function blinkLED() {
  blinkInterval = setInterval(() => {
    store.set(toggleAtom);
  }, 500);
}

How it works

  1. Call store.set using setInterval
  2. The value of lampAtom changes
  3. The callback subscribing to lampAtom is invoked
  4. Turn the LED ON/OFF within the callback


It lit up!

Discussion