Files
PapatMayuri 945086a15f updated with-context-api example to utilize the App Router. (#73316)
This PR updates the with-context-api example for using the App Router.
Here are the changes that have been made:

- I renamed the `pages` folder and moved it to the `app` folder.
- Added the `layout.tsx` file as part of the App Router.
- Moved `component` folder to `app` folder.
- Updated the package.json file.

CC: @samcx

---------

Co-authored-by: Sam Ko <sam@vercel.com>
2024-12-01 17:40:25 -08:00

60 lines
1.3 KiB
TypeScript

"use client";
import {
useReducer,
useContext,
createContext,
ReactNode,
Dispatch,
} from "react";
type CounterState = number;
type CounterAction =
| {
type: "INCREASE" | "DECREASE";
}
| {
type: "INCREASE_BY";
payload: number;
};
const CounterStateContext = createContext<CounterState>(0);
const CounterDispatchContext = createContext<Dispatch<CounterAction>>(
() => null,
);
const reducer = (state: CounterState, action: CounterAction) => {
switch (action.type) {
case "INCREASE":
return state + 1;
case "DECREASE":
return state - 1;
case "INCREASE_BY":
return state + action.payload;
default:
throw new Error(`Unknown action: ${JSON.stringify(action)}`);
}
};
type CounterProviderProps = {
children: ReactNode;
initialValue?: number;
};
export const CounterProvider = ({
children,
initialValue = 0,
}: CounterProviderProps) => {
const [state, dispatch] = useReducer(reducer, initialValue);
return (
<CounterDispatchContext.Provider value={dispatch}>
<CounterStateContext.Provider value={state}>
{children}
</CounterStateContext.Provider>
</CounterDispatchContext.Provider>
);
};
export const useCount = () => useContext(CounterStateContext);
export const useDispatchCount = () => useContext(CounterDispatchContext);