SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
Context API
Lucas Lira Gomes <@x8lucas8x>
Software Engineer
Passionate Hacker
ArchLinux Zealot
FOSS Enthusiast
I’m fond of doing
things that last
and all that jazz.
Lucas Lira Gomes
2
contact@x8lucas8x.com
linkedin.com/in/x8lucas8x
facebook.com/x8lucas8x
youtube.com/X80lucas08X
twitter.com/x8lucas8x
x8lucas8x.com
github.com/x8lucas8x
Context API
● Built in
○ React 16.3
● Solution for
○ “Prop-drilling”
That rings a bell
● Idea is not novel
○ Experimental API
■ 16.X
● Mobx
○ @inject
● React-intl
○ @injectIntl
● React-redux
○ @connect
● React-router
○ @withRouter
API Overview
● React.createContext(defaultValue);
○ <Producer value={...}/>
○ <Consumer>
{context => (...)}
</Consumer>
Single Context
import React, { Component } from 'react';
const ContextA = React.createContext();
class ParentComponent extends Component {
state = {data: "SomeValue"};
render() {
return (
<ContextA.Provider value={this.state}>
{this.props.children}
</ContextA.Provider>
...
const ChildComponent = () => (
<ContextA.Consumer>
{context=> <h1>{context.data}</h1>}
</ContextA.Consumer>
);
Multiple Contexts
import React, { Component } from 'react';
const ContextA = React.createContext();
const ContextB = React.createContext();
class ParentComponent extends Component {
state = {data: "SomeValue"};
render() {
return (
<ContextA.Provider value={this.state.dataA}>
<ContextB.Provider value={this.state.dataB}>
{this.props.children}
</ContextB.Provider>
</ContextA.Provider>
...
const ChildComponent = () => (
<ContextA.Consumer>
{ctxA => (
<ContextB.Consumer>
{ctxB => <h1>{ctxA} or {ctxB}</h1>}
</ContextB.Consumer>
)}
</ContextA.Consumer>
);
Updating the Context
...
const ContextB = React.createContext();
class ParentComponent extends Component {
state = {
isClicked: false,
onClick: () => this.setState({isClicked: true})
};
render() {
return (
<ContextA.Provider value={this.state}>
{this.props.children}
</ContextA.Provider>
...
const ChildComponent = () => (
<ContextA.Consumer>
{context => (
<button onClick={context.onClick}>
Click me!
</button>
)}
</ContextA.Consumer>
);
Applications
● “Global” for a tree
○ Localisation
○ Routing
○ Theme
○ User
○ ...
Good Practices
Avoid re-renders
● Use the state
○ Referential identity
import React, { Component } from 'react';
const ContextA = React.createContext();
class ParentComponent extends Component {
render() {
return (
<ContextA.Provider value={{clicked: true}}>
{this.props.children}
</ContextA.Provider>
...
Keep it DRY
● HOCs to the rescue
import React, { Component } from 'react';
const WhateverContext = React.createContext();
export function withWhatever(Component) {
return function ThemedComponent(props) {
return (
<WhateverContext.Consumer>
{context => (
<Component
{...props}
whatever={context.whatever}
/>
)}
</WhateverContext.Consumer>
);
};
}
References
1. https://reactjs.org/docs/context.html
13
Context API
Lucas Lira Gomes <@x8lucas8x>

Mais conteúdo relacionado

Mais procurados

An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.jsEmanuele DelBono
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
React web development
React web developmentReact web development
React web developmentRully Ramanda
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react formYao Nien Chung
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)Tomáš Drenčák
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksMaulik Shah
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to HooksSoluto
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_jsMicroPyramid .
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjsmanojbkalla
 
Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...
Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...
Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...GreeceJS
 

Mais procurados (20)

An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
React hooks
React hooksReact hooks
React hooks
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
React web development
React web developmentReact web development
React web development
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
State management in react applications (Statecharts)
State management in react applications (Statecharts)State management in react applications (Statecharts)
State management in react applications (Statecharts)
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
React and redux
React and reduxReact and redux
React and redux
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
React js
React jsReact js
React js
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
React JS
React JSReact JS
React JS
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
 
An Intro into webpack
An Intro into webpackAn Intro into webpack
An Intro into webpack
 
Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...
Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...
Introduction to react-query. A Redux alternative? (Nikos Kleidis, Front End D...
 
React hooks
React hooksReact hooks
React hooks
 

Semelhante a Context API in React

First steps with Gazebo simulation for ROS
First steps with Gazebo simulation for ROSFirst steps with Gazebo simulation for ROS
First steps with Gazebo simulation for ROSSergey Matyunin
 
From shipping rpms to helm charts - Lessons learned and best practices
From shipping rpms to helm charts - Lessons learned and best practicesFrom shipping rpms to helm charts - Lessons learned and best practices
From shipping rpms to helm charts - Lessons learned and best practicesAnkush Chadha, MBA, MS
 
Intro to Flutter
Intro to FlutterIntro to Flutter
Intro to FlutterEason Pai
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom componentsJeremy Grancher
 
Introduzione a React Native - Facebook Developer Circle Rome
Introduzione a React Native - Facebook Developer Circle RomeIntroduzione a React Native - Facebook Developer Circle Rome
Introduzione a React Native - Facebook Developer Circle RomeMatteo Manchi
 
EuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingEuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingAlessandro Molina
 
PyConUK 2014 - PostMortem Debugging and Web Development Updated
PyConUK 2014 - PostMortem Debugging and Web Development UpdatedPyConUK 2014 - PostMortem Debugging and Web Development Updated
PyConUK 2014 - PostMortem Debugging and Web Development UpdatedAlessandro Molina
 
How To Upgrade The React 18 Release Candidate.pptx
How To Upgrade The React 18 Release Candidate.pptxHow To Upgrade The React 18 Release Candidate.pptx
How To Upgrade The React 18 Release Candidate.pptxBOSC Tech Labs
 
Hands-on Lab: Red Hat Container Development & OpenShift
Hands-on Lab: Red Hat Container Development & OpenShiftHands-on Lab: Red Hat Container Development & OpenShift
Hands-on Lab: Red Hat Container Development & OpenShiftAmazon Web Services
 
Sep Nasiri "Upwork PHP Architecture"
Sep Nasiri "Upwork PHP Architecture"Sep Nasiri "Upwork PHP Architecture"
Sep Nasiri "Upwork PHP Architecture"Fwdays
 
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...Exploring the Functionality of the Rockwell Automation® Library of Process Ob...
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...Rockwell Automation
 
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...Exploring the Functionality of the Rockwell Automation® Library of Process Ob...
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...Rockwell Automation
 
Creando microservicios con java micro profile y tomee - CUNORI 2020
Creando microservicios con java micro profile y tomee - CUNORI 2020Creando microservicios con java micro profile y tomee - CUNORI 2020
Creando microservicios con java micro profile y tomee - CUNORI 2020César Hernández
 
RHEL8-BETA-RHUG.pdf
RHEL8-BETA-RHUG.pdfRHEL8-BETA-RHUG.pdf
RHEL8-BETA-RHUG.pdfHarsh Shah
 
Ready player 2 Multiplayer Red Teaming Against macOS
Ready player 2  Multiplayer Red Teaming Against macOSReady player 2  Multiplayer Red Teaming Against macOS
Ready player 2 Multiplayer Red Teaming Against macOSCody Thomas
 
Tech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboardsTech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboardsAppsilon Data Science
 

Semelhante a Context API in React (20)

Mobx
MobxMobx
Mobx
 
First steps with Gazebo simulation for ROS
First steps with Gazebo simulation for ROSFirst steps with Gazebo simulation for ROS
First steps with Gazebo simulation for ROS
 
From shipping rpms to helm charts - Lessons learned and best practices
From shipping rpms to helm charts - Lessons learned and best practicesFrom shipping rpms to helm charts - Lessons learned and best practices
From shipping rpms to helm charts - Lessons learned and best practices
 
Intro to Flutter
Intro to FlutterIntro to Flutter
Intro to Flutter
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom components
 
Introduzione a React Native - Facebook Developer Circle Rome
Introduzione a React Native - Facebook Developer Circle RomeIntroduzione a React Native - Facebook Developer Circle Rome
Introduzione a React Native - Facebook Developer Circle Rome
 
Search in Django
Search in DjangoSearch in Django
Search in Django
 
EuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears TrainingEuroPython 2013 - Python3 TurboGears Training
EuroPython 2013 - Python3 TurboGears Training
 
PyConUK 2014 - PostMortem Debugging and Web Development Updated
PyConUK 2014 - PostMortem Debugging and Web Development UpdatedPyConUK 2014 - PostMortem Debugging and Web Development Updated
PyConUK 2014 - PostMortem Debugging and Web Development Updated
 
Tranquilizer
TranquilizerTranquilizer
Tranquilizer
 
Ratpack 101 - GR8Conf 2015
Ratpack 101 - GR8Conf 2015Ratpack 101 - GR8Conf 2015
Ratpack 101 - GR8Conf 2015
 
How To Upgrade The React 18 Release Candidate.pptx
How To Upgrade The React 18 Release Candidate.pptxHow To Upgrade The React 18 Release Candidate.pptx
How To Upgrade The React 18 Release Candidate.pptx
 
Hands-on Lab: Red Hat Container Development & OpenShift
Hands-on Lab: Red Hat Container Development & OpenShiftHands-on Lab: Red Hat Container Development & OpenShift
Hands-on Lab: Red Hat Container Development & OpenShift
 
Sep Nasiri "Upwork PHP Architecture"
Sep Nasiri "Upwork PHP Architecture"Sep Nasiri "Upwork PHP Architecture"
Sep Nasiri "Upwork PHP Architecture"
 
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...Exploring the Functionality of the Rockwell Automation® Library of Process Ob...
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...
 
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...Exploring the Functionality of the Rockwell Automation® Library of Process Ob...
Exploring the Functionality of the Rockwell Automation® Library of Process Ob...
 
Creando microservicios con java micro profile y tomee - CUNORI 2020
Creando microservicios con java micro profile y tomee - CUNORI 2020Creando microservicios con java micro profile y tomee - CUNORI 2020
Creando microservicios con java micro profile y tomee - CUNORI 2020
 
RHEL8-BETA-RHUG.pdf
RHEL8-BETA-RHUG.pdfRHEL8-BETA-RHUG.pdf
RHEL8-BETA-RHUG.pdf
 
Ready player 2 Multiplayer Red Teaming Against macOS
Ready player 2  Multiplayer Red Teaming Against macOSReady player 2  Multiplayer Red Teaming Against macOS
Ready player 2 Multiplayer Red Teaming Against macOS
 
Tech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboardsTech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboards
 

Último

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Último (20)

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

Context API in React

  • 1. Context API Lucas Lira Gomes <@x8lucas8x>
  • 2. Software Engineer Passionate Hacker ArchLinux Zealot FOSS Enthusiast I’m fond of doing things that last and all that jazz. Lucas Lira Gomes 2 contact@x8lucas8x.com linkedin.com/in/x8lucas8x facebook.com/x8lucas8x youtube.com/X80lucas08X twitter.com/x8lucas8x x8lucas8x.com github.com/x8lucas8x
  • 3. Context API ● Built in ○ React 16.3 ● Solution for ○ “Prop-drilling”
  • 4. That rings a bell ● Idea is not novel ○ Experimental API ■ 16.X ● Mobx ○ @inject ● React-intl ○ @injectIntl ● React-redux ○ @connect ● React-router ○ @withRouter
  • 5. API Overview ● React.createContext(defaultValue); ○ <Producer value={...}/> ○ <Consumer> {context => (...)} </Consumer>
  • 6. Single Context import React, { Component } from 'react'; const ContextA = React.createContext(); class ParentComponent extends Component { state = {data: "SomeValue"}; render() { return ( <ContextA.Provider value={this.state}> {this.props.children} </ContextA.Provider> ... const ChildComponent = () => ( <ContextA.Consumer> {context=> <h1>{context.data}</h1>} </ContextA.Consumer> );
  • 7. Multiple Contexts import React, { Component } from 'react'; const ContextA = React.createContext(); const ContextB = React.createContext(); class ParentComponent extends Component { state = {data: "SomeValue"}; render() { return ( <ContextA.Provider value={this.state.dataA}> <ContextB.Provider value={this.state.dataB}> {this.props.children} </ContextB.Provider> </ContextA.Provider> ... const ChildComponent = () => ( <ContextA.Consumer> {ctxA => ( <ContextB.Consumer> {ctxB => <h1>{ctxA} or {ctxB}</h1>} </ContextB.Consumer> )} </ContextA.Consumer> );
  • 8. Updating the Context ... const ContextB = React.createContext(); class ParentComponent extends Component { state = { isClicked: false, onClick: () => this.setState({isClicked: true}) }; render() { return ( <ContextA.Provider value={this.state}> {this.props.children} </ContextA.Provider> ... const ChildComponent = () => ( <ContextA.Consumer> {context => ( <button onClick={context.onClick}> Click me! </button> )} </ContextA.Consumer> );
  • 9. Applications ● “Global” for a tree ○ Localisation ○ Routing ○ Theme ○ User ○ ...
  • 11. Avoid re-renders ● Use the state ○ Referential identity import React, { Component } from 'react'; const ContextA = React.createContext(); class ParentComponent extends Component { render() { return ( <ContextA.Provider value={{clicked: true}}> {this.props.children} </ContextA.Provider> ...
  • 12. Keep it DRY ● HOCs to the rescue import React, { Component } from 'react'; const WhateverContext = React.createContext(); export function withWhatever(Component) { return function ThemedComponent(props) { return ( <WhateverContext.Consumer> {context => ( <Component {...props} whatever={context.whatever} /> )} </WhateverContext.Consumer> ); }; }
  • 14. Context API Lucas Lira Gomes <@x8lucas8x>