0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jotai は React と特に関係ないライブラリなので L チカもできる

Last updated at Posted at 2025-06-11

タイトルは嘘です。React と関係あります。

しかしながら、React 依存部分と関係ないところは jotai/vanilla として分離されているので、React がなくても使えます。
この特徴は、React 以外の Vue などの他のフロントエンドで使えるだけでなく、ユニットテストやサーバーサイドでも活躍します。

ラズパイで L チカするコード

下のようなコードを書きました(一部抜粋)。
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();

// lampAtom の値を監視して LED 出力に反映する
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);
}

動き

  1. setIntervalstore.set する
  2. lampAtom の値が変わる
  3. lampAtom をサブスクライブするコールバックが呼ばれる
  4. コールバックで LED を ON/OFF する


光りました!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?