Sharing state with React context

React context allows state to be shared between components. It works really well with compound components. We are going to use it in our Tabs and Tab components to share state between them:

  1. Our first task is to create an interface for the context we are going to use in Tabs.tsx at the top of the file just beneath the import statements:
interface ITabsContext {  activeName?: string;  handleTabClick?: (name: string) => void;}

So, our context will contain the active tab name as well as a reference to a tab click handler. These are the two bits of state that need to be shared between the components.

  1. Next, let's create the context underneath the ITabsContext interface:
const TabsContext = React.createContext<ITabsContext>({}); ...

Get Learn React with TypeScript 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.