search

Home  >  Q&A  >  body text

React Context provider written in TypeScript

I'm new to React context and TypeScript, and I'm trying to write a context to open and close the sidebar. This is 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 context in my application, the boolean "activeMenu" works fine, which means the sidebar displays 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 closes the sidebar but the problem here is that the setter function "setActiveMenu" does not work at all . As I said, I'm new to both react context and typescript, no error is showing up in my console, and I don't know why this is happening.

P粉714780768P粉714780768298 days ago476

reply all(1)I'll reply

  • P粉727531237

    P粉7275312372024-03-29 16:09:43

    You are not storing your state anywhere and your context needs some support. try it

    export const ContextProvider = ({ children }: ContextProviderProps) => {
        const [activeMenu, setActiveMenu] = useState(true);
    
        return (
            
                {children}
            
        )
    }

    reply
    0
  • Cancelreply