Download react-use/src/factory/createReducerContext.ts from Devendra174/react-code-dataset: direct link, hf CLI and curl.
- Browser
- Download file 1.1 kB
-
https://huggingface.co/datasets/Devendra174/react-code-dataset/resolve/1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/react-use/src/factory/createReducerContext.ts
- Command line
-
hf download hf://datasets/Devendra174/react-code-dataset@1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/react-use/src/factory/createReducerContext.ts
-
curl -L -o createReducerContext.ts https://huggingface.co/datasets/Devendra174/react-code-dataset/resolve/1e92f2d0b9e054abc23a53595fd89ad3e2b4a34e/react-use/src/factory/createReducerContext.ts
1.1 kB
| import { createContext, createElement, useContext, useReducer } from 'react'; | |
| const createReducerContext = <R extends React.Reducer<any, any>>( | |
| reducer: R, | |
| defaultInitialState: React.ReducerState<R> | |
| ) => { | |
| const context = | |
| createContext<[React.ReducerState<R>, React.Dispatch<React.ReducerAction<R>>] | undefined>( | |
| undefined | |
| ); | |
| const providerFactory = (props, children) => createElement(context.Provider, props, children); | |
| const ReducerProvider = ({ | |
| children, | |
| initialState, | |
| }: { | |
| children?: React.ReactNode; | |
| initialState?: React.ReducerState<R>; | |
| }) => { | |
| const state = useReducer<R>( | |
| reducer, | |
| initialState !== undefined ? initialState : defaultInitialState | |
| ); | |
| return providerFactory({ value: state }, children); | |
| }; | |
| const useReducerContext = () => { | |
| const state = useContext(context); | |
| if (state == null) { | |
| throw new Error(`useReducerContext must be used inside a ReducerProvider.`); | |
| } | |
| return state; | |
| }; | |
| return [useReducerContext, ReducerProvider, context] as const; | |
| }; | |
| export default createReducerContext; | |