Skip to content

Instantly share code, notes, and snippets.

@ronaldruzicka
Last active February 9, 2021 08:21
Show Gist options
  • Save ronaldruzicka/67969bd2dd2c0004837bcce4345380d2 to your computer and use it in GitHub Desktop.
Save ronaldruzicka/67969bd2dd2c0004837bcce4345380d2 to your computer and use it in GitHub Desktop.
Example of simple React context in Typescript
import { createContext, useContext, useState } from 'react';
type Props = {
children: React.ReactNode | React.ReactNode[];
};
type Context = {
isExpanded: boolean;
toggleItem?: () => void;
};
const AccordionContext = createContext<Context>({
isExpanded: false,
toggleItem: undefined,
});
const AccordionProvider = ({ children }: Props) => {
const [isExpanded, setIsExpanded] = useState<boolean>(false);
const toggleItem = () => setIsExpanded((isExpanded) => !isExpanded);
return (
<AccordionContext.Provider value={{ isExpanded, toggleItem }}>
{children}
</AccordionContext.Provider>
);
};
const useAccordion = () => {
const context = useContext(AccordionContext);
if (typeof context === 'undefined') {
throw new Error('useAccordion must be used within a AccordionProvider');
}
return context;
};
export { AccordionProvider, useAccordion };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment