[React][Jotai][TypeScript]Jotai
/my-app
│── /src
│ ├── /state #状態定義フォルダ
│ │ ├── atoms.ts #Jotai 状態定義
│ ├── /components #コンポーネントフォルダ
│ │ ├── Search.tsx #コンポーネント1
│ │ ├── Info.tsx #コンポーネント2
│ ├── /App.tsx #アプリのエントリーポイント
│ ├── /main.tsx #React のルート
│── package.json
│── tsconfig.json
│── index.html
state/atoms.ts
import { atom } from "jotai"; // グローバルな状態(count)を定義 export const countAtom = atom(0);
components/Search.tsx
import { useAtom } from "jotai"; import { countAtom } from "../state/atoms"; const Search = () => { const [count] = useAtom(countAtom); return ( <div id="search" className="p-2.5 mb-2.5 bg-white"> <div>count:{count}</div> </div> ); }; export default Search;
components/Info.tsx
import { useAtom } from "jotai"; import { countAtom } from "../state/atoms"; const Info = () => { const [count, setCount] = useAtom(countAtom); // グローバル状態を取得&更新 return ( <div id="info" className="p-2.5 mb-2.5 bg-white"> <div> <h2>Count: {count}</h2> <button onClick={() => setCount((prev) => prev + 1)}>Increment</button> </div> </div> ); }; export default Info;
App.tsx
import { Provider } from "jotai"; import Search from './components/Search' import Info from './components/Info' const App = () => ( <Provider> <Search /> <Info /> </Provider> ); export default App;
main.tsx
import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import './index.css' import App from './App' createRoot(document.getElementById("app")!).render( <StrictMode> <App /> </StrictMode> );
<Provider>で囲われたアプリ、コンポーネント間でステートが共有される