Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
React Key Concepts

You're reading from   React Key Concepts Consolidate your knowledge of React's core features

Arrow left icon
Product type Paperback
Published in Dec 2022
Publisher Packt
ISBN-13 9781803234502
Length 590 pages
Edition 1st Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
Maximilian Schwarzmüller Maximilian Schwarzmüller
Author Profile Icon Maximilian Schwarzmüller
Maximilian Schwarzmüller
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface
1. React – What and Why FREE CHAPTER 2. Understanding React Components and JSX 3. Components and Props 4. Working with Events and State 5. Rendering Lists and Conditional Content 6. Styling React Apps 7. Portals and Refs 8. Handling Side Effects 9. Behind the Scenes of React and Optimization Opportunities 10. Working with Complex State 11. Building Custom React Hooks 12. Multipage Apps with React Router 13. Managing Data with React Router 14. Next Steps and Further Resources Appendix

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:

  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: [],
  addItem...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image