Initial React Context value.

Let's say my ContextProvider looks like -
type Action = {type: "modal_open"} | {type: "modal_close"}
type Dispatch = (action: Action) => void
type State = {isModalOpen: boolean}
type Props = {children: React.ReactNode};

const ExampleContext = createContext<{state: State; dispatch: Dispatch} | undefined>(undefined);

function exampleReducer(state: State, action: Action) {
switch (action.type) {
case "modal_open": {
return { ...state, isModalOpen: true };
}
case "modal_close": {
return { ...state, isModalOpen: false };
}
}
}

export const ExampleContextProvider = ({ children }: Props) => {
const [state, dispatch] = useReducer(exampleReducer, {
isModalOpen: false,
});

const value = { state, dispatch };
return (
<ExampleContext.Provider value={value}>
{children}
</ExampleContext.Provider>
);
};

export const useExample = () => {
const context = useContext(ExampleContext);
if (context === undefined) {
throw new Error(
"useExample must be used within a ExampleProvider"
);
}
return context;
};
type Action = {type: "modal_open"} | {type: "modal_close"}
type Dispatch = (action: Action) => void
type State = {isModalOpen: boolean}
type Props = {children: React.ReactNode};

const ExampleContext = createContext<{state: State; dispatch: Dispatch} | undefined>(undefined);

function exampleReducer(state: State, action: Action) {
switch (action.type) {
case "modal_open": {
return { ...state, isModalOpen: true };
}
case "modal_close": {
return { ...state, isModalOpen: false };
}
}
}

export const ExampleContextProvider = ({ children }: Props) => {
const [state, dispatch] = useReducer(exampleReducer, {
isModalOpen: false,
});

const value = { state, dispatch };
return (
<ExampleContext.Provider value={value}>
{children}
</ExampleContext.Provider>
);
};

export const useExample = () => {
const context = useContext(ExampleContext);
if (context === undefined) {
throw new Error(
"useExample must be used within a ExampleProvider"
);
}
return context;
};
Now is it ok for me to pass the initial value for the reducer state via props to the ExampleProvider as follows -
type Props = {children: React.ReactNode, initialModalState: boolean};

export const ExampleContextProvider = ({ children, initialModalState }: Props) => {
const [state, dispatch] = useReducer(exampleReducer, {
isModalOpen: initialModalState,
});

const value = { state, dispatch };
return (
<ExampleContext.Provider value={value}>
{children}
</ExampleContext.Provider>
);
};
type Props = {children: React.ReactNode, initialModalState: boolean};

export const ExampleContextProvider = ({ children, initialModalState }: Props) => {
const [state, dispatch] = useReducer(exampleReducer, {
isModalOpen: initialModalState,
});

const value = { state, dispatch };
return (
<ExampleContext.Provider value={value}>
{children}
</ExampleContext.Provider>
);
};
Just want to make sure I'm not following some incorrect pattern.
0 Replies
No replies yetBe the first to reply to this messageJoin