SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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)
 

Kürzlich hochgeladen

2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Data modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainData modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainAbdul Ahad
 

Kürzlich hochgeladen (20)

2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Data modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software DomainData modeling 101 - Basics - Software Domain
Data modeling 101 - Basics - Software Domain
 

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