Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React, createContext default value problem with useState hook

In my React application with TypeScript, I want to create a context for a component. The createContext shows an error when a default value is not provided. One of the values I want to pass is the setFilters which is a hook dispatcher. How should I provide a default value?

Also, I do not want it optional, to prevent ! from invocation.

    export interface ContextProps {
      filters: FiltersType;
      setFilters: React.Dispatch<React.SetStateAction<FiltersType>>;
    }
    
    export const MyContext = React.createContext<ContextProps>({
      filters: defaultFilters, // imported from constants holder
      setFilters: // <---- What should be here?
    });
    
    const FiltersContext: React.FC<IProps> = (props: IProps) => {
      const [filters, setFilters] = React.useState<FiltersType>(defaultFilters);
    
      return <MyContext.Provider value={{ filters, setFilters }}>{props.children}</MyContext.Provider>;
    };
    
    export default FiltersContext;
like image 706
Amir-Mousavi Avatar asked Jul 04 '26 07:07

Amir-Mousavi


1 Answers

The default value is used when no context provider is available, so it depends what do you want to do in such situation. You can throw an error, then use setFilters: () => { throw new Error('No FiltersContext available'); }, or silently ignore it, then setFilters: () => {} would do, or whatever you want to do.

like image 180
amik Avatar answered Jul 05 '26 21:07

amik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!