Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { createContext, useContext, useReducer } from 'react';
- interface Counter {
- count: number;
- random: number;
- }
- const initialState = {count: 0, random: 0.5};
- // type Action = {type: 'increment'} | {type: 'setRandom'}
- type Actiontype = 'increment' | 'setRandom';
- type Action = { type: Actiontype, payload?: any }
- type Dispatch = (action: Action) => void;
- function countReducer(state: Counter, action: Action) {
- switch (action.type) {
- case 'increment':
- return { ...state, count: state.count + 1}
- case 'setRandom':
- return { ...state, random: Math.random()}
- }
- return state;
- }
- const CountStateContext = createContext<!!|>(undefined);
- const CountDispatchContext = createContext<Dispatch>(() => null);
- export default function App() {
- const [state, dispatch] = useReducer(countReducer, initialState)
- return <div>
- <CountStateContext.Provider value={state}>
- <CountDispatchContext.Provider value={dispatch}>
- <button onClick={() => dispatch({ type: 'increment'})}>+</button>
- <button onClick={() => dispatch({ type: 'setRandom'})}>Random</button>
- <hr/>
- <Dashboard />
- </CountDispatchContext.Provider>
- </CountStateContext.Provider>
- </div>
- }
- export const Dashboard = React.memo(() => {
- console.log('dashboard')
- return <div>
- <Panel1 />
- <Panel2 />
- </div>
- })
- export const Panel1 = () => {
- console.log('panel 1')
- const state = useContext(CountStateContext)
- return <div>
- Panel1 {JSON.stringify(state)}
- </div>
- }
- /**
- * Not rendered since it's not using CountStateContext
- * @constructor
- */
- export const Panel2 = () => {
- console.log('panel 2')
- const dispatch = useContext(CountDispatchContext);
- return <div>
- Panel 2: <button onClick={() => dispatch({ type: 'increment'})}>+ (from child)</button>
- </div>
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement