5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

react: stateの共有 (props無し、redux無し)

Last updated at Posted at 2020-07-12

方法

  1. useStateをモジュールに切り分ける。(下記appMode.tsの、function useAppMode参照)
  2. 一番外側のコンポーネントで、モジュール化されたuseState(下記のfunction useAppMode)を呼ぶ。
  3. 以後、任意のコンポーネントで、ステート(下記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)
}
5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?