Search code examples
reactjstypescriptreact-context

React Context provider with TypeScript


I'm new to React context and TypeScript, and I'm trying to write and context to toggle a side bar on and off. Here's my code

import React, { createContext, useContext, ReactNode, SetStateAction, Dispatch } from "react";



interface StateContextType {
    activeMenu: boolean
    setActiveMenu: Dispatch<SetStateAction<boolean>>;
}

export const StateContext = createContext<StateContextType>({
    activeMenu: true,
    setActiveMenu: () => {}
});



type ContextProviderProps = {
    children?: ReactNode
}

export const ContextProvider = ({ children }: ContextProviderProps) => {
    
    return (
        <StateContext.Provider
            value={{ activeMenu: true, setActiveMenu: () => { } }}
        >
            {children}
        </StateContext.Provider>
    )
}

export const useStateContext = () => useContext(StateContext)

When I try to use the context in my app, the boolean "activeMenu" is working fine, meaning that the side bar is shown based on its value. Because I set its default value to true, the sidebar is shown and when I change it manually from the context provider it toggles the sidebar off, but the problem here is that the setter function "setActiveMenu" is not working at all. As I said I'm new to both react context and typescript, there're no errors displayed in my console, and I have no clue why this's happing.


Solution

  • You're not storing your state anywhere and your context needs some backing. Try

    export const ContextProvider = ({ children }: ContextProviderProps) => {
        const [activeMenu, setActiveMenu] = useState(true);
    
        return (
            <StateContext.Provider value={{ activeMenu, setActiveMenu }}>
                {children}
            </StateContext.Provider>
        )
    }