A presentation at Granite State Code Camp by Kemet Dugue
Context in React Kemet Dugue kemetdugue kdugue
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
About Me ● Engineer at ● Some Interests: ○ Lo fi / chill ○ yoga Whatever your heart desires!
Opinions and Q+A
Props and Passing Data
Prop Drilling ● Pass props through components that don’t need it ● Downsides: ○ Unintended Mutations ○ Dependency on the intermediary components ○ Re-renders in intermediary components
“Context provides a way to pass data through the component tree without having to pass pros down manually at every level” - React Docs
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
Without Context With Context
Context Use Cases ● Theming ● Localization ● User data ● Non-frequently changing data
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
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
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
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
Questions????
Context in React