方法
- useStateをモジュールに切り分ける。(下記appMode.tsの、function useAppMode参照)
- 一番外側のコンポーネントで、モジュール化されたuseState(下記のfunction useAppMode)を呼ぶ。
- 以後、任意のコンポーネントで、ステート(下記appMode.tsの mode)、ステートのsetter(下記appMode.tsのsetMode)が参照可能となる。
appMode.ts
import { useState, Dispatch, SetStateAction } from 'react'
export enum AppMode {
home,
write,
read,
}
export let mode: AppMode
export let setMode: Dispatch<SetStateAction<AppMode>>
export function useAppMode() {
;[mode, setMode] = useState(AppMode.home)
}
例
-
appMode.ts
-
app.tsx
- home.tsx
- write.tsx
- read.tsx
app.tsx
import {
isHomeMode,
isWriteMode,
isReadMode,
useAppMode,
} from '../logic/appMode'
import { Reader } from '../components/reader'
import { Writer } from '../components/writer'
import { Home } from '../components/home'
export default () => {
useAppMode() // モジュール化したuseStateを呼び出し
return (
<div id="app">
{isHomeMode() ? <Home></Home> : null} // stateをgetterで参照
{isWriteMode() ? <Writer></Writer> : null}
{isReadMode() ? <Reader></Reader> :
</div>
)
}
home.tsx
import { setWriteMode } from '../logic/appMode'
import { setReadMode } from '../logic/appMode'
export const Home = () => (
<div>
<button onClick={() => setWriteMode()}>Write</button>
<button onClick={() => setReadMode()}>Read</button> // stateのsetterを呼び出し
</div>
)
appMode.ts
import { useState, Dispatch, SetStateAction } from 'react'
enum AppMode {
home,
write,
read,
}
let mode: AppMode
let setMode: Dispatch<SetStateAction<AppMode>>
export function useAppMode() {
;[mode, setMode] = useState(AppMode.home)
}
// getter setter (※不要。上記、mode, setMode, AppModeをexportすればよい。可読性と保守性にメリット。)
export function isHomeMode(): boolean {
return mode == AppMode.home
}
export function isWriteMode(): boolean {
return mode == AppMode.write
}
export function isReadMode(): boolean {
return mode == AppMode.read
}
export function setHomeMode(): void {
setMode(AppMode.home)
}
export function setWriteMode(): void {
setMode(AppMode.write)
}
export function setReadMode(): void {
setMode(AppMode.read)
}