SlideShare une entreprise Scribd logo
1  sur  48
Télécharger pour lire hors ligne
September 2018
Powering Code Reuse

with Context and Render Props
Forbes Lindesay
Thanks to our sponsors!
FUNCTIONS AS FIRST
CLASS VALUES
DOUBLE/TRIPPLE ARRAY
function doubleArr(vs) {
const result = [];
for (let i=0;i<vs.length;i ++) {
result.push(vs[i] * 2);
}
return result;
}
// input: [1, 2, 3]
// output: [2, 4, 6]
function trippleArr(vs) {
const result = [];
for (let i=0;i<vs.length;i ++) {
result.push(vs[i] * 3);
}
return result;
}
// input: [1, 2, 3]
// output: [3, 6, 9]
function trippleArr(vs) {
const result = [];
for (let i=0;i<vs.length;i ++) {
result.push(vs[i] * 3);
}
return result;
}
// input: [1, 2, 3]
// output: [3, 6, 9]
function doubleArr(vs) {
const result = [];
for (let i=0;i<vs.length;i ++) {
result.push(vs[i] * 2);
}
return result;
}
// input: [1, 2, 3]
// output: [2, 4, 6]
DOUBLE/TRIPPLE ARRAY
function multiplyArr(vs, factor) {
const result = [];
for (let i=0;i<vs.length;i ++) {
result.push(vs[i] * factor);
}
return result;
}
MULTIPLY ARRAY
MULTIPLY/ADD ARRAY
function multiplyArr(vs, factor) {
const result = [];
for (let i=0;i<vs.length;i ++) {
result.push(vs[i] * factor);
}
return result;
}
// input: [1, 2, 3], 3
// output: [3, 6, 9]
function addArr(vs, increment) {
const result = [];
for (let i=0;i<vs.length;i ++) {
result.push(vs[i] + increment);
}
return result;
}
// input: [1, 2, 3], 3
// output: [4, 5, 6]
function multiplyArr(vs, factor) {
const result = [];
for (let i=0;i<vs.length;i ++) {
result.push(vs[i] * factor);
}
return result;
}
// input: [1, 2, 3], 3
// output: [3, 6, 9]
function addArr(vs, increment) {
const result = [];
for (let i=0;i<vs.length;i ++) {
result.push(vs[i] + increment);
}
return result;
}
// input: [1, 2, 3], 3
// output: [4, 5, 6]
MULTIPLY/ADD ARRAY
function mapArray(vs, fn) {
const result = [];
for (let i=0;i<vs.length;i ++) {
result.push(fn(vs[i]));
}
return result;
}
MAP ARRAY
MAP ARRAY
function mapArray(vs, fn) {
return vs.map(fn);
}
REACT PROPERTIES
ARE PARAMETERS
REACT NOW
class Now extends React.Component {
state = {now: new Date()};
componentDidMount() {
this._timer = setInterval(
() => this.setState({now: new Date()}),
100,
);
}
componentWillUnmount() {
clearInterval(this._timer);
}
render() {
return this.state.now.toString();
}
}
REACT NOW
class UTCNow extends React.Component {
state = {now: new Date()};
componentDidMount() {
this._timer = setInterval(
() => this.setState({now: new Date()}),
100,
);
}
componentWillUnmount() {
clearInterval(this._timer);
}
render() {
return this.state.now.toUTCString();
}
}
class UTCNow extends React.Component {
state = {now: new Date()};
componentDidMount() {
this._timer = setInterval(
() => this.setState({now: new Date()}),
100,
);
}
componentWillUnmount() {
clearInterval(this._timer);
}
render() {
return this.state.now.toUTCString();
}
}
REACT NOW
REACT NOW
class Now extends React.Component {
state = {now: new Date()};
componentDidMount() {
this._timer = setInterval(
() => this.setState({now: new Date()}),
100,
);
}
componentWillUnmount() {
clearInterval(this._timer);
}
render() {
return this.state.now.[
this.props.utc ? 'toUTCString' : 'toString'
]();
}
}
REACT NOW
class Now extends React.Component {
state = {now: new Date()};
componentDidMount() {
this._timer = setInterval(
() => this.setState({now: new Date()}),
100,
);
}
componentWillUnmount() {
clearInterval(this._timer);
}
render() {
return this.props.render(this.state.now);
}
}
REACT NOW
function LocalTime() {
return <Now render={now => now.toTimeString()} />;
}
function UTCTime() {
return <Now render={now => now.toUTCTimeString()} />;
}
function LocalDateTime() {
return <Now render={now => now.toString()} />;
}
function UTCDateTime() {
return <Now render={now => now.toUTCString()} />;
}
DATE FORMATTING
Fri Sep 14 2018 15:47:26 GMT+0200 (Central European
Summer Time)
<strong>Fri Sep 14 2018 </strong> 15:47:26
GMT+0200 (Central European Summer Time)
REACT NOW
function DateTime() {
return (
<Now render={now => (
<React.Fragment>
<strong>{now.toDateString()} </strong>
{' ' + now.toTimeString()}
</React.Fragment>
)} />
);
}
“CHILDREN” IS JUST
A SPECIAL PROPERTY
REACT NOW
class Now extends React.Component {
state = {now: new Date()};
componentDidMount() {
this._timer = setInterval(
() => this.setState({now: new Date()}),
100,
);
}
componentWillUnmount() {
clearInterval(this._timer);
}
render() {
return this.props.render(this.state.now);
}
}
REACT NOW
class Now extends React.Component {
state = {now: new Date()};
componentDidMount() {
this._timer = setInterval(
() => this.setState({now: new Date()}),
100,
);
}
componentWillUnmount() {
clearInterval(this._timer);
}
render() {
return this.props.children(this.state.now);
}
}
function DateTime() {
return (
<Now render={now => (
<React.Fragment>
<strong>{now.toDateString()} </strong>
{' ' + now.toTimeString()}
</React.Fragment>
)} />
);
}
REACT NOW
REACT NOW
function DateTime() {
return (
<Now>
{now => (
<React.Fragment>
<strong>{now.toDateString()} </strong>
{' ' + now.toTimeString()}
</React.Fragment>
)}
</Now>
);
}
STATE IS ANYTHING THAT
CHANGES OVER TIME
REACT TREE
COMPONENT
COMPONENT COMPONENT
COMPONENT COMPONENTCOMPONENTCOMPONENT
COMPONENT COMPONENT COMPONENT COMPONENTCOMPONENTCOMPONENT
REACT TREE
COMPONENT
COMPONENT COMPONENT
COMPONENT COMPONENTCOMPONENTCOMPONENT
COMPONENT COMPONENT COMPONENT COMPONENTCOMPONENTA
REACT TREE
COMPONENT
COMPONENT COMPONENT
COMPONENT COMPONENTCOMPONENTCOMPONENT
COMPONENT COMPONENT COMPONENT COMPONENTBA
REACT TREE
COMPONENT
COMPONENT COMPONENT
PARENT COMPONENTCOMPONENTCOMPONENT
COMPONENT COMPONENT COMPONENT COMPONENTBA
REACT TREE
COMPONENT
COMPONENT COMPONENT
PARENT COMPONENTCOMPONENTCOMPONENT
COMPONENT C COMPONENT COMPONENTBA
REACT TREE
ROOT
COMPONENT COMPONENT
PARENT COMPONENTCOMPONENTCOMPONENT
COMPONENT C COMPONENT COMPONENTBA
REACT TREE
ROOT
COMPONENT COMPONENT
PARENT COMPONENTCOMPONENTCOMPONENT
COMPONENT C COMPONENT COMPONENTBA
REACT TREE
ROOT
COMPONENT COMPONENT
COMPONENT COMPONENTCOMPONENTCOMPONENT
COMPONENT C COMPONENT COMPONENTBA
External Store?
REACT TREE
ROOT
COMPONENT COMPONENT
COMPONENT COMPONENTCOMPONENTCOMPONENT
COMPONENT C COMPONENT COMPONENTBA
REACT TREE
ROOT
COMPONENT COMPONENT
COMPONENT COMPONENTCOMPONENTCOMPONENT
COMPONENT C COMPONENT COMPONENTBA
REACT TREE
ROOT
SHARED
PARENT COMPONENT
COMPONENT COMPONENTCOMPONENT
C
COMPONENT
COMPONENT COMPONENT COMPONENTBA
REACT TREE
ROOT
SHARED
PARENT COMPONENT
COMPONENT COMPONENT
C
COMPONENT
COMPONENT D EBA
SHARED
PARENT 2
const Color = React.createContext('black');
function ThemedCircle() {
return (
<Color.Consumer>
{color => <Circle color={color} />}
</Color.Consumer>
)
}
<React.Fragment>
<Color.Provider value="blue">
<ThemedCircle /><ThemedCircle /><ThemedCircle />
</Color.Provider>
<Color.Provider value="red">
<ThemedCircle /><ThemedCircle /><ThemedCircle />
</Color.Provider>
<ThemedCircle /><ThemedCircle /><ThemedCircle />
</React.Fragment>
const Color = React.createContext('black');
function ThemedCircle() {
return (
<Color.Consumer>
{color => <Circle color={color} />}
</Color.Consumer>
)
}
<React.Fragment>
<Color.Provider value="blue">
<ThemedCircle /><ThemedCircle /><ThemedCircle />
</Color.Provider>
<Color.Provider value="red">
<ThemedCircle /><ThemedCircle /><ThemedCircle />
</Color.Provider>
<ThemedCircle /><ThemedCircle /><ThemedCircle />
</React.Fragment>
const Color = React.createContext('black');
function ThemedCircle() {
return (
<Color.Consumer>
{color => <Circle color={color} />}
</Color.Consumer>
)
}
<React.Fragment>
<Color.Provider value="blue">
<ThemedCircle /><ThemedCircle /><ThemedCircle />
</Color.Provider>
<Color.Provider value="red">
<ThemedCircle /><ThemedCircle /><ThemedCircle />
</Color.Provider>
<ThemedCircle /><ThemedCircle /><ThemedCircle />
</React.Fragment>
const Toggle = React.createContext({on: false, onToggle: () => {}});
class ToggleProvider extends React.Component {
state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))};
render() {
return (
<Toggle.Provider value={this.state}>
{this.props.children}
</Toggle.Provider>
);
}
}
function ToggleButton() {
return (
<Toggle.Consumer>
{({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>}
</Toggle.Consumer>
)
}
<ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider>
const Toggle = React.createContext({on: false, onToggle: () => {}});
class ToggleProvider extends React.Component {
state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))};
render() {
return (
<Toggle.Provider value={this.state}>
{this.props.children}
</Toggle.Provider>
);
}
}
function ToggleButton() {
return (
<Toggle.Consumer>
{({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>}
</Toggle.Consumer>
)
}
<ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider>
const Toggle = React.createContext({on: false, onToggle: () => {}});
class ToggleProvider extends React.Component {
state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))};
render() {
return (
<Toggle.Provider value={this.state}>
{this.props.children}
</Toggle.Provider>
);
}
}
function ToggleButton() {
return (
<Toggle.Consumer>
{({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>}
</Toggle.Consumer>
)
}
<ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider>
const Toggle = React.createContext({on: false, onToggle: () => {}});
class ToggleProvider extends React.Component {
state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))};
render() {
return (
<Toggle.Provider value={this.state}>
{this.props.children}
</Toggle.Provider>
);
}
}
function ToggleButton() {
return (
<Toggle.Consumer>
{({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>}
</Toggle.Consumer>
)
}
<ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider>
OFF OFF OFF
const Toggle = React.createContext({on: false, onToggle: () => {}});
class ToggleProvider extends React.Component {
state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))};
render() {
return (
<Toggle.Provider value={this.state}>
{this.props.children}
</Toggle.Provider>
);
}
}
function ToggleButton() {
return (
<Toggle.Consumer>
{({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>}
</Toggle.Consumer>
)
}
<ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider>
ON ON ON
const Toggle = React.createContext({on: false, onToggle: () => {}});
class ToggleProvider extends React.Component {
state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))};
render() {
return (
<Toggle.Provider value={this.state}>
{this.props.children}
</Toggle.Provider>
);
}
}
function ToggleButton() {
return (
<Toggle.Consumer>
{({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>}
</Toggle.Consumer>
)
}
<ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider>
OFF OFF OFF
const Toggle = React.createContext({on: false, onToggle: () => {}});
class ToggleProvider extends React.Component {
state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))};
render() {
return (
<Toggle.Provider value={this.state}>
{this.props.children}
</Toggle.Provider>
);
}
}
function ToggleButton() {
return (
<Toggle.Consumer>
{({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>}
</Toggle.Consumer>
)
}
<ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider>
ON ON ON
SUMMARY
▸ Functions being first class values means we can use them as
parameters to enable more flexible code re-use
▸ Using functions as parameters allows highly customisable
shared components, complete with state and lifecycle hooks.
▸ React Context lets you share state across the tree of your
application
▸ Context still uses the React tree. This means it works with
server side rendering and you can safely use it in parts of your
app, as well as using it as a whole app solution.
@ForbesLindesay

Contenu connexe

Tendances

React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hypeMagdiel Duarte
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J ScriptRoman Agaev
 
Big data unit iv and v lecture notes qb model exam
Big data unit iv and v lecture notes   qb model examBig data unit iv and v lecture notes   qb model exam
Big data unit iv and v lecture notes qb model examIndhujeni
 
An introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduceAn introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduceAnanth PackkilDurai
 
How MapReduce part of Hadoop works (i.e. system's view) ?
How MapReduce part of Hadoop works (i.e. system's view) ? How MapReduce part of Hadoop works (i.e. system's view) ?
How MapReduce part of Hadoop works (i.e. system's view) ? Niketan Pansare
 
Chapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsChapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsVincent Chien
 
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
 
A quick introduction to R
A quick introduction to RA quick introduction to R
A quick introduction to RAngshuman Saha
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react applicationGreg Bergé
 
Higher-Order Components — Ilya Gelman
Higher-Order Components — Ilya GelmanHigher-Order Components — Ilya Gelman
Higher-Order Components — Ilya Gelman500Tech
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstituteSuresh Loganatha
 
What's new for developers in Dynamics 365 v9: Client API enhancement
What's new for developers in Dynamics 365 v9: Client API enhancementWhat's new for developers in Dynamics 365 v9: Client API enhancement
What's new for developers in Dynamics 365 v9: Client API enhancementKenichiro Nakamura
 
React Back to the Future
React Back to the FutureReact Back to the Future
React Back to the Future500Tech
 
Deep Dive into React Hooks
Deep Dive into React HooksDeep Dive into React Hooks
Deep Dive into React HooksFelix Kühl
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesKaniska Mandal
 
Testing in those hard to reach places
Testing in those hard to reach placesTesting in those hard to reach places
Testing in those hard to reach placesdn
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga beginsDaniel Franz
 

Tendances (20)

React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hype
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J Script
 
Big data unit iv and v lecture notes qb model exam
Big data unit iv and v lecture notes   qb model examBig data unit iv and v lecture notes   qb model exam
Big data unit iv and v lecture notes qb model exam
 
Gwt RPC
Gwt RPCGwt RPC
Gwt RPC
 
An introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduceAn introduction to Test Driven Development on MapReduce
An introduction to Test Driven Development on MapReduce
 
How MapReduce part of Hadoop works (i.e. system's view) ?
How MapReduce part of Hadoop works (i.e. system's view) ? How MapReduce part of Hadoop works (i.e. system's view) ?
How MapReduce part of Hadoop works (i.e. system's view) ?
 
Clojure functions midje
Clojure functions midjeClojure functions midje
Clojure functions midje
 
Chapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsChapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfs
 
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
 
A quick introduction to R
A quick introduction to RA quick introduction to R
A quick introduction to R
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react application
 
Higher-Order Components — Ilya Gelman
Higher-Order Components — Ilya GelmanHigher-Order Components — Ilya Gelman
Higher-Order Components — Ilya Gelman
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
 
What's new for developers in Dynamics 365 v9: Client API enhancement
What's new for developers in Dynamics 365 v9: Client API enhancementWhat's new for developers in Dynamics 365 v9: Client API enhancement
What's new for developers in Dynamics 365 v9: Client API enhancement
 
React Back to the Future
React Back to the FutureReact Back to the Future
React Back to the Future
 
Deep Dive into React Hooks
Deep Dive into React HooksDeep Dive into React Hooks
Deep Dive into React Hooks
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml Classes
 
Testing in those hard to reach places
Testing in those hard to reach placesTesting in those hard to reach places
Testing in those hard to reach places
 
The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
Zenddispatch en
Zenddispatch enZenddispatch en
Zenddispatch en
 

Similaire à Powering code reuse with context and render props

JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"GeeksLab Odessa
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render PropsNitish Phanse
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs[T]echdencias
 
React for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence ConnectReact for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence ConnectAtlassian
 
Dive into React Performance
Dive into React PerformanceDive into React Performance
Dive into React PerformanceChing Ting Wu
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wildJoe Morgan
 
react-hooks.pdf
react-hooks.pdfreact-hooks.pdf
react-hooks.pdfchengbo xu
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 DreamLab
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7Dongho Cho
 
Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2Ahmed Moawad
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab AcademyDreamLab
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)RichardWarburton
 
What is new in sulu 2.0
What is new in sulu 2.0What is new in sulu 2.0
What is new in sulu 2.0danrot
 
Super TypeScript II Turbo - FP Remix (NG Conf 2017)
Super TypeScript II Turbo - FP Remix (NG Conf 2017)Super TypeScript II Turbo - FP Remix (NG Conf 2017)
Super TypeScript II Turbo - FP Remix (NG Conf 2017)Sean May
 

Similaire à Powering code reuse with context and render props (20)

JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
React lecture
React lectureReact lecture
React lecture
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
 
React for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence ConnectReact for Re-use: Creating UI Components with Confluence Connect
React for Re-use: Creating UI Components with Confluence Connect
 
Dive into React Performance
Dive into React PerformanceDive into React Performance
Dive into React Performance
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
react-hooks.pdf
react-hooks.pdfreact-hooks.pdf
react-hooks.pdf
 
React hooks
React hooksReact hooks
React hooks
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 
Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab Academy
 
Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)
 
React/Redux
React/ReduxReact/Redux
React/Redux
 
What is new in sulu 2.0
What is new in sulu 2.0What is new in sulu 2.0
What is new in sulu 2.0
 
Super TypeScript II Turbo - FP Remix (NG Conf 2017)
Super TypeScript II Turbo - FP Remix (NG Conf 2017)Super TypeScript II Turbo - FP Remix (NG Conf 2017)
Super TypeScript II Turbo - FP Remix (NG Conf 2017)
 

Dernier

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Dernier (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

Powering code reuse with context and render props

  • 1. September 2018 Powering Code Reuse with Context and Render Props Forbes Lindesay
  • 2. Thanks to our sponsors!
  • 4. DOUBLE/TRIPPLE ARRAY function doubleArr(vs) { const result = []; for (let i=0;i<vs.length;i ++) { result.push(vs[i] * 2); } return result; } // input: [1, 2, 3] // output: [2, 4, 6] function trippleArr(vs) { const result = []; for (let i=0;i<vs.length;i ++) { result.push(vs[i] * 3); } return result; } // input: [1, 2, 3] // output: [3, 6, 9]
  • 5. function trippleArr(vs) { const result = []; for (let i=0;i<vs.length;i ++) { result.push(vs[i] * 3); } return result; } // input: [1, 2, 3] // output: [3, 6, 9] function doubleArr(vs) { const result = []; for (let i=0;i<vs.length;i ++) { result.push(vs[i] * 2); } return result; } // input: [1, 2, 3] // output: [2, 4, 6] DOUBLE/TRIPPLE ARRAY
  • 6. function multiplyArr(vs, factor) { const result = []; for (let i=0;i<vs.length;i ++) { result.push(vs[i] * factor); } return result; } MULTIPLY ARRAY
  • 7. MULTIPLY/ADD ARRAY function multiplyArr(vs, factor) { const result = []; for (let i=0;i<vs.length;i ++) { result.push(vs[i] * factor); } return result; } // input: [1, 2, 3], 3 // output: [3, 6, 9] function addArr(vs, increment) { const result = []; for (let i=0;i<vs.length;i ++) { result.push(vs[i] + increment); } return result; } // input: [1, 2, 3], 3 // output: [4, 5, 6]
  • 8. function multiplyArr(vs, factor) { const result = []; for (let i=0;i<vs.length;i ++) { result.push(vs[i] * factor); } return result; } // input: [1, 2, 3], 3 // output: [3, 6, 9] function addArr(vs, increment) { const result = []; for (let i=0;i<vs.length;i ++) { result.push(vs[i] + increment); } return result; } // input: [1, 2, 3], 3 // output: [4, 5, 6] MULTIPLY/ADD ARRAY
  • 9. function mapArray(vs, fn) { const result = []; for (let i=0;i<vs.length;i ++) { result.push(fn(vs[i])); } return result; } MAP ARRAY
  • 10. MAP ARRAY function mapArray(vs, fn) { return vs.map(fn); }
  • 12. REACT NOW class Now extends React.Component { state = {now: new Date()}; componentDidMount() { this._timer = setInterval( () => this.setState({now: new Date()}), 100, ); } componentWillUnmount() { clearInterval(this._timer); } render() { return this.state.now.toString(); } }
  • 13. REACT NOW class UTCNow extends React.Component { state = {now: new Date()}; componentDidMount() { this._timer = setInterval( () => this.setState({now: new Date()}), 100, ); } componentWillUnmount() { clearInterval(this._timer); } render() { return this.state.now.toUTCString(); } }
  • 14. class UTCNow extends React.Component { state = {now: new Date()}; componentDidMount() { this._timer = setInterval( () => this.setState({now: new Date()}), 100, ); } componentWillUnmount() { clearInterval(this._timer); } render() { return this.state.now.toUTCString(); } } REACT NOW
  • 15. REACT NOW class Now extends React.Component { state = {now: new Date()}; componentDidMount() { this._timer = setInterval( () => this.setState({now: new Date()}), 100, ); } componentWillUnmount() { clearInterval(this._timer); } render() { return this.state.now.[ this.props.utc ? 'toUTCString' : 'toString' ](); } }
  • 16. REACT NOW class Now extends React.Component { state = {now: new Date()}; componentDidMount() { this._timer = setInterval( () => this.setState({now: new Date()}), 100, ); } componentWillUnmount() { clearInterval(this._timer); } render() { return this.props.render(this.state.now); } }
  • 17. REACT NOW function LocalTime() { return <Now render={now => now.toTimeString()} />; } function UTCTime() { return <Now render={now => now.toUTCTimeString()} />; } function LocalDateTime() { return <Now render={now => now.toString()} />; } function UTCDateTime() { return <Now render={now => now.toUTCString()} />; }
  • 18. DATE FORMATTING Fri Sep 14 2018 15:47:26 GMT+0200 (Central European Summer Time) <strong>Fri Sep 14 2018 </strong> 15:47:26 GMT+0200 (Central European Summer Time)
  • 19. REACT NOW function DateTime() { return ( <Now render={now => ( <React.Fragment> <strong>{now.toDateString()} </strong> {' ' + now.toTimeString()} </React.Fragment> )} /> ); }
  • 20. “CHILDREN” IS JUST A SPECIAL PROPERTY
  • 21. REACT NOW class Now extends React.Component { state = {now: new Date()}; componentDidMount() { this._timer = setInterval( () => this.setState({now: new Date()}), 100, ); } componentWillUnmount() { clearInterval(this._timer); } render() { return this.props.render(this.state.now); } }
  • 22. REACT NOW class Now extends React.Component { state = {now: new Date()}; componentDidMount() { this._timer = setInterval( () => this.setState({now: new Date()}), 100, ); } componentWillUnmount() { clearInterval(this._timer); } render() { return this.props.children(this.state.now); } }
  • 23. function DateTime() { return ( <Now render={now => ( <React.Fragment> <strong>{now.toDateString()} </strong> {' ' + now.toTimeString()} </React.Fragment> )} /> ); } REACT NOW
  • 24. REACT NOW function DateTime() { return ( <Now> {now => ( <React.Fragment> <strong>{now.toDateString()} </strong> {' ' + now.toTimeString()} </React.Fragment> )} </Now> ); }
  • 25. STATE IS ANYTHING THAT CHANGES OVER TIME
  • 26. REACT TREE COMPONENT COMPONENT COMPONENT COMPONENT COMPONENTCOMPONENTCOMPONENT COMPONENT COMPONENT COMPONENT COMPONENTCOMPONENTCOMPONENT
  • 27. REACT TREE COMPONENT COMPONENT COMPONENT COMPONENT COMPONENTCOMPONENTCOMPONENT COMPONENT COMPONENT COMPONENT COMPONENTCOMPONENTA
  • 28. REACT TREE COMPONENT COMPONENT COMPONENT COMPONENT COMPONENTCOMPONENTCOMPONENT COMPONENT COMPONENT COMPONENT COMPONENTBA
  • 29. REACT TREE COMPONENT COMPONENT COMPONENT PARENT COMPONENTCOMPONENTCOMPONENT COMPONENT COMPONENT COMPONENT COMPONENTBA
  • 30. REACT TREE COMPONENT COMPONENT COMPONENT PARENT COMPONENTCOMPONENTCOMPONENT COMPONENT C COMPONENT COMPONENTBA
  • 31. REACT TREE ROOT COMPONENT COMPONENT PARENT COMPONENTCOMPONENTCOMPONENT COMPONENT C COMPONENT COMPONENTBA
  • 32. REACT TREE ROOT COMPONENT COMPONENT PARENT COMPONENTCOMPONENTCOMPONENT COMPONENT C COMPONENT COMPONENTBA
  • 33. REACT TREE ROOT COMPONENT COMPONENT COMPONENT COMPONENTCOMPONENTCOMPONENT COMPONENT C COMPONENT COMPONENTBA External Store?
  • 34. REACT TREE ROOT COMPONENT COMPONENT COMPONENT COMPONENTCOMPONENTCOMPONENT COMPONENT C COMPONENT COMPONENTBA
  • 35. REACT TREE ROOT COMPONENT COMPONENT COMPONENT COMPONENTCOMPONENTCOMPONENT COMPONENT C COMPONENT COMPONENTBA
  • 36. REACT TREE ROOT SHARED PARENT COMPONENT COMPONENT COMPONENTCOMPONENT C COMPONENT COMPONENT COMPONENT COMPONENTBA
  • 37. REACT TREE ROOT SHARED PARENT COMPONENT COMPONENT COMPONENT C COMPONENT COMPONENT D EBA SHARED PARENT 2
  • 38. const Color = React.createContext('black'); function ThemedCircle() { return ( <Color.Consumer> {color => <Circle color={color} />} </Color.Consumer> ) } <React.Fragment> <Color.Provider value="blue"> <ThemedCircle /><ThemedCircle /><ThemedCircle /> </Color.Provider> <Color.Provider value="red"> <ThemedCircle /><ThemedCircle /><ThemedCircle /> </Color.Provider> <ThemedCircle /><ThemedCircle /><ThemedCircle /> </React.Fragment>
  • 39. const Color = React.createContext('black'); function ThemedCircle() { return ( <Color.Consumer> {color => <Circle color={color} />} </Color.Consumer> ) } <React.Fragment> <Color.Provider value="blue"> <ThemedCircle /><ThemedCircle /><ThemedCircle /> </Color.Provider> <Color.Provider value="red"> <ThemedCircle /><ThemedCircle /><ThemedCircle /> </Color.Provider> <ThemedCircle /><ThemedCircle /><ThemedCircle /> </React.Fragment>
  • 40. const Color = React.createContext('black'); function ThemedCircle() { return ( <Color.Consumer> {color => <Circle color={color} />} </Color.Consumer> ) } <React.Fragment> <Color.Provider value="blue"> <ThemedCircle /><ThemedCircle /><ThemedCircle /> </Color.Provider> <Color.Provider value="red"> <ThemedCircle /><ThemedCircle /><ThemedCircle /> </Color.Provider> <ThemedCircle /><ThemedCircle /><ThemedCircle /> </React.Fragment>
  • 41. const Toggle = React.createContext({on: false, onToggle: () => {}}); class ToggleProvider extends React.Component { state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))}; render() { return ( <Toggle.Provider value={this.state}> {this.props.children} </Toggle.Provider> ); } } function ToggleButton() { return ( <Toggle.Consumer> {({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>} </Toggle.Consumer> ) } <ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider>
  • 42. const Toggle = React.createContext({on: false, onToggle: () => {}}); class ToggleProvider extends React.Component { state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))}; render() { return ( <Toggle.Provider value={this.state}> {this.props.children} </Toggle.Provider> ); } } function ToggleButton() { return ( <Toggle.Consumer> {({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>} </Toggle.Consumer> ) } <ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider>
  • 43. const Toggle = React.createContext({on: false, onToggle: () => {}}); class ToggleProvider extends React.Component { state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))}; render() { return ( <Toggle.Provider value={this.state}> {this.props.children} </Toggle.Provider> ); } } function ToggleButton() { return ( <Toggle.Consumer> {({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>} </Toggle.Consumer> ) } <ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider>
  • 44. const Toggle = React.createContext({on: false, onToggle: () => {}}); class ToggleProvider extends React.Component { state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))}; render() { return ( <Toggle.Provider value={this.state}> {this.props.children} </Toggle.Provider> ); } } function ToggleButton() { return ( <Toggle.Consumer> {({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>} </Toggle.Consumer> ) } <ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider> OFF OFF OFF
  • 45. const Toggle = React.createContext({on: false, onToggle: () => {}}); class ToggleProvider extends React.Component { state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))}; render() { return ( <Toggle.Provider value={this.state}> {this.props.children} </Toggle.Provider> ); } } function ToggleButton() { return ( <Toggle.Consumer> {({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>} </Toggle.Consumer> ) } <ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider> ON ON ON
  • 46. const Toggle = React.createContext({on: false, onToggle: () => {}}); class ToggleProvider extends React.Component { state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))}; render() { return ( <Toggle.Provider value={this.state}> {this.props.children} </Toggle.Provider> ); } } function ToggleButton() { return ( <Toggle.Consumer> {({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>} </Toggle.Consumer> ) } <ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider> OFF OFF OFF
  • 47. const Toggle = React.createContext({on: false, onToggle: () => {}}); class ToggleProvider extends React.Component { state = {on: false, onToggle: () => this.setState(s => ({on: !s.on}))}; render() { return ( <Toggle.Provider value={this.state}> {this.props.children} </Toggle.Provider> ); } } function ToggleButton() { return ( <Toggle.Consumer> {({on, onToggle}) => <button onClick={onToggle}>{on ? 'on' : 'off'} </button>} </Toggle.Consumer> ) } <ToggleProvider><ToggleButton /><ToggleButton /><ToggleButton /> </ToggleProvider> ON ON ON
  • 48. SUMMARY ▸ Functions being first class values means we can use them as parameters to enable more flexible code re-use ▸ Using functions as parameters allows highly customisable shared components, complete with state and lifecycle hooks. ▸ React Context lets you share state across the tree of your application ▸ Context still uses the React tree. This means it works with server side rendering and you can safely use it in parts of your app, as well as using it as a whole app solution. @ForbesLindesay