10. Working with Complex State
Activity 10.1: Migrating an App to the Context API
Solution:
Perform the following solution steps to complete this activity:
- As a first step, create a
store/cart-context.js
file. This file will hold the context object and theProvider
component that contains the cross-component state logic (which is exposed via theProvider
component). - In the newly added
cart-context.js
file, create a newCartContext
via React'screateContext()
function. To get better IDE auto-completion, the initial context value can be set to an object that has anitems
property (an empty array) and two methods: an (empty)addItem
and an (empty)removeItem
method. The created context also must be exported, so that it can be referenced by other project files.
This is the final cart-context.js file content (for the moment):
import { createContext } from 'react'; const CartContext = createContext({ items: [], addItem...