SlideShare una empresa de Scribd logo
1 de 14
Descargar para leer sin conexión
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>

Más contenido relacionado

La actualidad más candente

Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
State Management in Angular/React
State Management in Angular/ReactState Management in Angular/React
State Management in Angular/ReactDEV Cafe
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJSKnoldus Inc.
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to ReactRob Quick
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 
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 .
 
How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...Katy Slemon
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesWalking Tree Technologies
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksMaulik Shah
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack IntroductionAnjali Chawla
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsANKUSH CHAVAN
 
Angular state Management-NgRx
Angular state Management-NgRxAngular state Management-NgRx
Angular state Management-NgRxKnoldus Inc.
 

La actualidad más candente (20)

Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
React context
React context  React context
React context
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
State Management in Angular/React
State Management in Angular/ReactState Management in Angular/React
State Management in Angular/React
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
React hooks
React hooksReact hooks
React hooks
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
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
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
ReactJS
ReactJSReactJS
ReactJS
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack Introduction
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Angular state Management-NgRx
Angular state Management-NgRxAngular state Management-NgRx
Angular state Management-NgRx
 
React js
React jsReact js
React js
 

Similar 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
 

Similar 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

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Último (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

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>