Search⌘ K

Placing the Context

Explore how to create and use React context with TypeScript interfaces, implement the useReducer hook for state management, and provide state and dispatch through context to child components, enabling efficient and scalable state handling in your React applications.

Okay, now for the fun part. Here’s the App component:

TypeScript 3.3.4
import * as React from "react"
import { Venue } from "./venue"
import {
TicketData,
VenueAction,
VenueState,
initialState,
venueReducer,
} from "./venue_reducer"
export interface AppProps {
concertId: number
rows: number
seatsInRow: number
otherHeldTickets: TicketData[]
}
export interface IsVenueContext {
state: VenueState
dispatch: React.Dispatch<VenueAction>
}
export const VenueContext = React.createContext<IsVenueContext>(null)
export const App = (props: AppProps) => {
const [state, dispatch] = React.useReducer(
venueReducer,
initialState(props)
)
return (
<VenueContext.Provider value={{ state, dispatch }}>
<Venue />
</VenueContext.Provider>
)
}

Declarations

Most of this is declarations. We start by importing from React and then importing our Venue component, and a new file called venue_reducer that I’ll talk about in a moment. Then we declare two TypeScript interfaces, one for the AppProps and one for the context called IsVenueContext. The props interface just holds all the data we just passed to this component as props: the concert ID, the number of rows, the number of seats in a row, and the list of already held tickets.

Creating the context

The IsVenueContext is a bit more interesting. It has two elements: a state element of type VenueState, which is defined in the reducer file, and a dispatch element of type ...