0% found this document useful (0 votes)
8 views

sharing-state-and-functions-via-context-slides

Uploaded by

harsh090101kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

sharing-state-and-functions-via-context-slides

Uploaded by

harsh090101kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Managing State with

Context

Cory House
React Consultant and Trainer

@housecor | reactjsconsulting.com
Agenda
Why context?
Use context to share our cart
- Wrap provider in a custom component
- Share context via a custom hook
Do I need context?
Plain JS React React Context Redux

Simple Complex
No setup Significant setup
What if components in different parts of your app need the same data?
User data

User data
3 Solutions
1. Lift State

User data, “lifted” to common ancestor


3 Solutions
1. Lift State

User data, “lifted” to common ancestor

...and passed down to children


3 Solutions
1. Lift State

2 components need user data.

But 6 other components must


pass it down on props.

Problem: Prop Drilling


So is “prop drilling” bad?
3 Solutions
1. Lift State
2. React context

User data

User data
3 Solutions
1. Lift State
2. React context

UserContext.Provider
(Holds user data and funcs)
Call createUser via context

UserContext.Consumer

UserContext.Consumer
3 Solutions
1. Lift State
2. React context Store
3. Redux

Action: Create User


3 Solutions
1. Lift State
2. React context Store
3. Redux

New user data New user data


When are Context or Redux Helpful?

Global data and functions


Complex data flows
Inter-component communication

Many actions
My Take

1. Start with state in a single component

2. Lift state as needed

3. Try context or Redux when lifting state gets annoying


Global data or functions?
- Consider context or Redux
Summary
Context: Two pieces:
- Provider: Provides data/funcs
- Consumer: Consumes data/funcs

Consider “wrapping” context


- Provider component
- useContext hook
- Require context provider
Up Next:

Managing State in Third Party Libraries

You might also like