✒️
SEI 802
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Learning Objectives
  • What is Context in React
  • Appropriate Use Cases
  • Using Context
  • Create a Context
  • Context Providers
  • Context Consumers
  • Accessing Context in Function Components
  • Accessing Context in Class Components
  • Accessing Multiple Contexts
  • Note on Hooks
  • Alternatives to Context
  • Extra Resources

Was this helpful?

  1. React (Updated 2019)
  2. Additional Topics

Context API

PreviousTypeScriptNextReact Native

Last updated 3 years ago

Was this helpful?

Learning Objectives

After this lesson, you will be able to:

  • Define Context and distinguish a Context.Provider from a Context.Consumer

  • Use the React Context API to pass data and functions across the Component Tree

  • Identify appropriate use cases for React Context

What is Context in React

From the :

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

In short, the Context API gives as a method to work around prop-drilling in certain situations.

We have learned that React has a uni-directonal flow of data, only passing data or functions from parent to child via props. Using Context allows us to use data or functions that we would consider global within our Component tree without passing them through each level of a branch.

A Context is composed of three parts: the definition, the Provider and the Consumer. Aptly named, the Provider will provide access to the data that we want to make available, and the Consumer will be used where we want to use the data provided.

You may have already been using Context whether you knew it or not. React Router is an example of the Context API in use! Behind the scenes, React Router has created a Context that includes location, history, match and helper functions to deal with navigation. It grants access via the<BrowserRouter /> and <Link /> components.

/* App.js */
<BrowserRouter> // Context Provider
  <Router exact path='/' component={Home} />
  <Router ... />   
  <Router ... />  
</BrowserRouter>


/* NavComponent.jsx */
<Link to='/'>Home</Link> // Context Consumers 
<Link to='/issues'>Issues</Link>
<Link to='/pullrequests'>Pull Requests</Link>

Appropriate Use Cases

  • Authenticated User Data

  • Theming

  • Localization data

Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.

Using Context

Create a Context

Touch a new file in src to house your Context code. You can define and export data and function stubs to be used by Context. When creating your context make sure that the shape of your Context data matches what you will use be using in your Context Providers and Consumers

// ColorContext.js
import React from 'react';

// global array of colors that we will use
export const colors = ['black', 'blue', 'green', 'rebeccapurple', 'red', 'whitesmoke'];

//make sure that the Context matches the signature that your Consumer will expect later
export const ColorContext = React.createContext({
  color: '',
  changeColor: () => {} // emtpy function <= we will apply a function to in our Provider
});

Context Providers

Import the Context (and any data) into the Component that you intend to provide data from.

/* App.js */
...
import { ColorContext, colors } from './ColorContext';
...

Wrap the portion of your Component tree in which you intend to use the data with a Context Provider and pass the data to it as a value prop.

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      color: colors[0],
      changeColor: this.changeColor // wait, whattttt?! methods in state?! you better believe it
    }
  }

  changeColor = () => {
    // color change logic goes here
  }

  render() {
    return(
      <ColorContext.Provider value={this.state}>
        {/* Child Components */}
      </ColorContext.Provider>
    )
  }
}

Context Consumers

Within the child component where data should be displayed, import the Context and wrap the portion of the component with a Context.Consumer. Your context data will be accessible through an anonymous function.

Accessing Context in Function Components

/* ColorPane.jsx */
export function ColorPane(props) {
  return(
    <ColorContext.Consumer>
      { // open a block
        ({color}) => { // Anonymous function with destructuring syntax to access `color` from the Context
          let style = {
            background: color, // this is our Context color!
            height: "200px", 
            width: "200px"
          }
          return (
            <div style={style}></div>
          )
        }
      }
    </ColorContext.Consumer>
  )
}
/* ColorButton.jsx */
export function Colorbutton(props) {
  return(
    {
      ({changeColor}) => <button onClick={changeColor}>CHANGE THE COLOR</button> // yup, just like that
    }
  )
}

Accessing Context in Class Components

Class Components offer another method of accessing Context data by assigning a context to the Component.contextType property. This method only works when access to a single Context is required.

import React from 'react';
import { ColorContext } from './ColorContext'

class ColorPane extends React.Component {
  render() {
    let style = {
      background: this.context.color, // We can access data in the this.context object
      height: "200px", 
      width: "200px"
    }

    return (
      <div style={style}></div>
    )
  }
}

ColorPane.contextType = ColorContext; // Assign context after class is defined

export default ColorPane;

Accessing Multiple Contexts

You can use data from multiple Contexts in the following manner

...
<ColorContext.Consumer>
  { ({color}) => (
      <UserContext.Consumer>
      { user => (
          <MyComponent user={user} themeColor={color} />
        ) 
      }
      </UserContext.Consumer>
    )
  }
</ColorContext.Consumer>

...

Note on Hooks

Alternatives to Context

Containment

// ParentContainer.jsx
export const ParentContainer = props => {
  return(
    <div>
      {props.children}
    </div>
  )
}


// App.jsx 
...
render() {
  return(
    <ParentContainer some={someProps}> 
        <ChildComponent diffe={rentProps} /> 
        <AnotherChild someOth={erProps} /> 
    </ParentContainer>`
  )
}
...

Passed

//Parent.jsx
import React from 'react';
import { ChildOne } from './ChildOne'

export function Parent(props) {
  return (
    <ChildOne {...props} />
  )
}

// ChildOne.jsx
import React from 'react';

export function ChildOne(props) {
  return (
    <div>
      {props.usedDownTheTree}
    </div>
    )
}

// UsedDownTheTree.jsx
import React from 'react';

export function UsedDownTheTree(props) {
  return(
    <>
      <h1>Hello, {props.name ? props.name : 'World!'}</h1>
      <h3>{props.message ? props.message : '' }</h3>
    </>
  )
}

//App.js
import React, { Component } from 'react';
import {Parent} from './Parent'
import {UsedDownTheTree} from './UsedDownTheTree';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      user: 'GLaDOS',
      message: "I don't like lemonade"
    }
  }


  render() {
    let usedDownTheTree = <UsedDownTheTree name={this.state.user} message={this.state.message}/>
    return (
      <div className="App">
          <Parent usedDownTheTree={usedDownTheTree}/>
      </div>
    );
  }
}

export default App;

Extra Resources

The has provided a useContext hook to allow access to your Contexts within function components.

Redux -

React Docs
new Hooks API*
Component Composition Patterns
Docs
Hackernoon - how to use Context API