LoginSignup
1
0

More than 3 years have passed since last update.

Recoilで動的に初期stateを与える方法

Last updated at Posted at 2020-07-12

やりたいこと

みんな大好きstate管理の雄、Recoil
ユニットテストをするときや初期状態をどこかのオラクルから与えたい場合の書き方が公式docを見てもわかりづらかったのでメモ

こうする

RecoilRootinitializeStateとして、初期値をsetしてあげる。

state.js
import { atom, selector } from "recoil"

export const hogeState = atom({
  key: "hogeState",
  default: true,
})
App.js
import { RecoilRoot } from "recoil"
import { hogeState } from "./state"

const initializeState = ({ set }) => {
  // 必要に応じて対象のステート及び値を設定するロジックを追加
  set(hogeState, false)
}

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <RecoilRoot initializeState={initializeState}>
      <Component {...pageProps} />
    </RecoilRoot>
  )
}

export default MyApp


かんたんですね。

Recoil、とてもdeveloperフレンドリーなライブラリで好きです。

参考

1
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
1
0