Book Image

React Key Concepts

By : Maximilian Schwarzmüller
Book Image

React Key Concepts

By: Maximilian Schwarzmüller

Overview of this book

As the most popular JavaScript library for building modern, interactive user interfaces, React is an in-demand framework that’ll bring real value to your career or next project. But like any technology, learning React can be tricky, and finding the right teacher can make things a whole lot easier. Maximilian Schwarzmüller is a bestselling instructor who has helped over two million students worldwide learn how to code, and his latest React video course (React — The Complete Guide) has over six hundred thousand students on Udemy. Max has written this quick-start reference to help you get to grips with the world of React programming. Simple explanations, relevant examples, and a clear, concise approach make this fast-paced guide the ideal resource for busy developers. This book distills the core concepts of React and draws together its key features with neat summaries, thus perfectly complementing other in-depth teaching resources. So, whether you've just finished Max’s React video course and are looking for a handy reference tool, or you've been using a variety of other learning materials and now need a single study guide to bring everything together, this is the ideal companion to support you through your next React projects. Plus, it's fully up to date for React 18, so you can be sure you’re ready to go with the latest version.
Table of Contents (16 chapters)

10. Working with Complex State

Activity 10.1: Migrating an App to the Context API


Perform the following solution steps to complete this activity:

  1. As a first step, create a store/cart-context.js file. This file will hold the context object and the Provider component that contains the cross-component state logic (which is exposed via the Provider component).
  2. In the newly added cart-context.js file, create a new CartContext via React's createContext() function. To get better IDE auto-completion, the initial context value can be set to an object that has an items 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: [],