25
25

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.

[TypeScript/React Hooks] useReducer + useContextで死ぬほど簡単にグローバルなストアを作る

Last updated at Posted at 2019-11-09
import React, {
    createContext,
    FC,
    useContext,
    useEffect,
    useReducer,
} from 'react'

type NewStateAction = Partial<S> | ((prevState: S) => Partial<S>)
type ContextValue = {
    globalState: S
    setGlobalState: (newState: NewStateAction) => void
}

type S = typeof initialState

const initialState = {
    count: 0,
}

export const Store = createContext({} as ContextValue)

export const Provider: FC<{}> = ({ children }) => {
    const [globalState, setGlobalState] = useReducer(
        (prev: S, newState: NewStateAction) => {
            const _newState =
                typeof newState === 'function' ? newState(prev) : newState
            return { ...prev, ..._newState }
        },
        initialState,
    )

    useEffect(() => {
        // count が変更された場合の処理
    }, [globalState.count])

    return (
        <Store.Provider value={{ globalState, setGlobalState }}>
            {children}
        </Store.Provider>
    )
}

おわり。勢いで書いたのでどっか間違ってるかもしれません。

コンポーネントでは以下のように使います。

const Component = props => {
    const { globalState, setGlobalState } = useContext(Store)

    globalState.count // get

    setGlobalState({ count: 1 }) // set
    setGlobalState(({ count }) => ({ count: count + 1 })) // set
}

const App = () => (
    <Provider>
        <Component></Component>
    </Provider>
)

useEffect など通常の React Hooks の API が使えるので統一感があっていいですね!!

25
25
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
25
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?