ReactのuseStateからJotaiのuseAtomへ

1 min read読了の目安(約1200字

https://twitter.com/dai_shi/status/1397756674669088768

jotaiの簡単な使い方を説明するためにuseStateを使ったカウンターの例をuseAtomでglobal stateにするものです。

useStateのコード

import { useState } from "react";

const Counter1 = () => {
  const [count, setCount] = useState(0);
  const inc = () => setCount((c) => c + 1);
  return <div> {count} <button onClick={inc}>+1</button> </div>;
};

const Counter2 = () => {
  const [count, setCount] = useState(0);
  const inc = () => setCount((c) => c + 1);
  return <div> {count} <button onClick={inc}>+1</button> </div>;
};

const App = () => (
  <>
    <Counter1 />
    <Counter2 />
  </>
);

useAtomのコード

import { useState } from "react";
import { atom, useAtom } from "jotai";

const countAtom = atom(0)

const Counter1 = () => {
  const [count, setCount] = useAtom(countAtom);
  const inc = () => setCount((c) => c + 1);
  return <div> {count} <button onClick={inc}>+1</button> </div>;
};

const Counter2 = () => {
  const [count, setCount] = useAtom(countAtom);
  const inc = () => setCount((c) => c + 1);
  return <div> {count} <button onClick={inc}>+1</button> </div>;
};

const App = () => (
  <>
    <Counter1 />
    <Counter2 />
  </>
);