Context in React

A presentation at Granite State Code Camp in November 2021 in by Kemet Dugue

Slide 1

Slide 1

Context in React Kemet Dugue kemetdugue kdugue

Slide 2

Slide 2

Agenda 1. Brief Introduction 2. React Context a. Props and Overall Goal of Context b. Introduction & Examples c. Best Practices and Usage Decisions 3. Resources 4. Q+A

Slide 3

Slide 3

About Me ● Engineer at ● Some Interests: ○ Lo fi / chill ○ yoga Whatever your heart desires!

Slide 4

Slide 4

Opinions and Q+A

Slide 5

Slide 5

Props and Passing Data

Slide 6

Slide 6

Prop Drilling ● Pass props through components that don’t need it ● Downsides: ○ Unintended Mutations ○ Dependency on the intermediary components ○ Re-renders in intermediary components

Slide 7

Slide 7

“Context provides a way to pass data through the component tree without having to pass pros down manually at every level” - React Docs

Slide 8

Slide 8

Using Context: 3 Parts 1. Context Object a. Creates context that will hold some information 2. Provider a. Declare the data in component tree that will be available to components that consume it 3. Consumer a. Allows components to subscribed to data from Provider

Slide 9

Slide 9

Without Context With Context

Slide 10

Slide 10

Slide 11

Slide 11

Slide 12

Slide 12

Context Use Cases ● Theming ● Localization ● User data ● Non-frequently changing data

Slide 13

Slide 13

Re-Renders and Performance ● Only components that call useContext will re-render whenever the context’s state changes ● Every component that consumes a given context re-renders every time that context’s state changes

Slide 14

Slide 14

Best Practices ● For Stateful Context, be sure to have the update state logic not defined in the Context itself ● Use Multiple Contexts, and keep state close to its Dependent Components

Slide 15

Slide 15

Deciding to Use Context Not a good idea when: Possibly a good idea when: ● Trying to replace state or state management tool (Redux) ● Making a portion of your React component tree more accessible ● Replace every instance of props passing (2-3 levels is okay) ● Static, or non-frequently changing data

Slide 16

Slide 16

Resources ● React docs on Context: https://reactjs.org/docs/context.html ● Memoizing Context: https://github.com/facebook/react/issues/15156#issuecomment-47459 0693 ● Prop Drilling: https://kentcdodds.com/blog/prop-drilling

Slide 17

Slide 17

Questions????