SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
State Management
in a World of Hooks
Maayan Glikser Adam Klein
&
Maayan Glikser
Developer, Consultant, Trainer
CTO @ 500Tech
What are hooks?
React Conf 2018
Hooks let us organize stateful
logic inside components into
reusable isolated units.
How did we share logic between
components in the past?
React 0.x
Mixins
Mixins
const MouseMixin = {
getInitialState() {
return { x: 0, y: 0 }
},
handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
})
}
}
Mixins
const App = React.createClass({
// Use the mixin!
mixins: [ MouseMixin ],
render() {
const { x, y } = this.state
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
<h1>The mouse position is ({x}, {y})</h1>
</div>
)
}
})
React 15+
Higher Order Components
Higher Order Component (HoC)
function logProps(WrappedComponent) {
return class extends React.Component {
componentWillReceiveProps(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
}
render() {
// Wraps the input component in a container, without mutating it. Good!
return <WrappedComponent {...this.props} />;
}
}
}
Higher Order Component (HoC)
const AppWithLog = logProps(App);
Wrapper Hell
Render Props
class Mouse extends React.Component {
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
})
}
render() {
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
)
}
}
Render Props
const App = () => (
<div>
<Mouse render={({ x, y }) => (
// The render prop gives us the state we need
// to render whatever we want here.
<h1>The mouse position is ({x}, {y})</h1>
)}/>
</div>
);
const MyForm = () => (
<DataFetcher>
{( data ) => (
<Actions>
{( actions ) => (
<Translations>
{( translations ) => (
<Styles>
{(styles) => (
<form style={styles}>
<input type="text" value={data.value} />
<button onClick={action.submit}>
{ translations.submitText }
</button>
</form>
)}
</Styles>
)}
</Translations>
)}
</Actions>
)}
</DataFetcher>
);
Hooks
Hooks are stateful
small units of logic
which are easy to reuse and test.
const App = () => {
const [user, setRole, ROLES] = useUser();
return (
<div style={{ height: '100%' }}>
Welcome { user }
<button onClick={() => setRole(ROLES.ADMIN)}>
Make Admin
</button>
</div>
);
};
const useUser = () => {
const ROLES = { ADMIN: 'ADMIN', CLIENT: 'CLIENT' };
const [user, setUser] = useState(null);
const setAdmin = useCallback((role) => {
setUser({ ...user, role });
}, [user]);
return [user, setAdmin, ROLES];
};
How do we share data
between components?
Lift State Up
React Context
<App />
<User />
UsersProvider
Logged In Username
UsersConsumer
const App = () => (
<Provider>
<Provider1>
<Provider2>
<Provider3>
<Provider4>
<Provider5>
<Layout />
</Provider5>
</Provider4>
</Provider3>
</Provider2>
</Provider1>
</Provider>
);
const App = () => (
<Layout>
<UsersProvider>
<Header />
</UsersProvider>
<AccountsProvider>
<AccountScreen />
</AccountsProvider>
<Footer />
</Layout>
);
When Context
Isn't enough
Where do we
go from here?
External State Managment
<App />
<Layout />
<Header /> <Accounts />
<User />
Store
Users Accounts
State Managment React Component Tree
Direct Subscriptions
Render Bailout
Moving from Context to State
Managment
Large refactor
What if it could be easier?
Developer, Consultant, Trainer

CEO @ 500Tech

I love dad jokes
Adam Klein
Thank You
Maayan Glikser Adam Klein
&
https://github.com/adamkleingit/reusable-talk
https://github.com/reusablejs/reusable
@maayanglikser
@adamklein500

Weitere ähnliche Inhalte

Ähnlich wie State managment in a world of hooks

Big Data for each one of us
Big Data for each one of usBig Data for each one of us
Big Data for each one of us
OSCON Byrum
 
Mobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhoneMobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhone
Mohammad Shaker
 

Ähnlich wie State managment in a world of hooks (20)

Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
 
Big Data for each one of us
Big Data for each one of usBig Data for each one of us
Big Data for each one of us
 
React hooks
React hooksReact hooks
React hooks
 
A comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter componentA comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter component
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creators
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
Mobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhoneMobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhone
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Android 3
Android 3Android 3
Android 3
 
Advanced React Component Patterns - ReactNext 2018
Advanced React Component Patterns - ReactNext 2018Advanced React Component Patterns - ReactNext 2018
Advanced React Component Patterns - ReactNext 2018
 
Stay with React.js in 2020
Stay with React.js in 2020Stay with React.js in 2020
Stay with React.js in 2020
 
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the WireUn-Framework - Delivering Dynamic Experiences with HTML over the Wire
Un-Framework - Delivering Dynamic Experiences with HTML over the Wire
 
Building complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and ReactBuilding complex User Interfaces with Sitecore and React
Building complex User Interfaces with Sitecore and React
 
Introduction to React and MobX
Introduction to React and MobXIntroduction to React and MobX
Introduction to React and MobX
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
Academy PRO: React native - building first scenes
Academy PRO: React native - building first scenesAcademy PRO: React native - building first scenes
Academy PRO: React native - building first scenes
 
Egghead redux-cheat-sheet-3-2-1
Egghead redux-cheat-sheet-3-2-1Egghead redux-cheat-sheet-3-2-1
Egghead redux-cheat-sheet-3-2-1
 
course js day 3
course js day 3course js day 3
course js day 3
 

Mehr von 500Tech

Mehr von 500Tech (20)

React Under the Hook - DevDays Europe 2019
React Under the Hook - DevDays Europe 2019React Under the Hook - DevDays Europe 2019
React Under the Hook - DevDays Europe 2019
 
React Back to the Future
React Back to the FutureReact Back to the Future
React Back to the Future
 
Hooks - why should you care today?
Hooks - why should you care today?Hooks - why should you care today?
Hooks - why should you care today?
 
Migrating from angular to react
Migrating from angular to reactMigrating from angular to react
Migrating from angular to react
 
How to write bad code in redux (ReactNext 2018)
How to write bad code in redux (ReactNext 2018)How to write bad code in redux (ReactNext 2018)
How to write bad code in redux (ReactNext 2018)
 
Opinionated Approach to Redux
Opinionated Approach to ReduxOpinionated Approach to Redux
Opinionated Approach to Redux
 
Mobx Internals
Mobx InternalsMobx Internals
Mobx Internals
 
Mobx - Performance and Sanity
Mobx - Performance and SanityMobx - Performance and Sanity
Mobx - Performance and Sanity
 
Mobx Performance and Sanity
Mobx Performance and SanityMobx Performance and Sanity
Mobx Performance and Sanity
 
Mobx - performance and sanity
Mobx - performance and sanityMobx - performance and sanity
Mobx - performance and sanity
 
Tales of an open source library
Tales of an open source libraryTales of an open source library
Tales of an open source library
 
Angular2 a modern web platform
Angular2   a modern web platformAngular2   a modern web platform
Angular2 a modern web platform
 
Angular. MobX. Happiness
Angular. MobX. HappinessAngular. MobX. Happiness
Angular. MobX. Happiness
 
Render to DOM
Render to DOMRender to DOM
Render to DOM
 
Managing state in Angular 1.x with Redux
Managing state in Angular 1.x with ReduxManaging state in Angular 1.x with Redux
Managing state in Angular 1.x with Redux
 
Higher-Order Components — Ilya Gelman
Higher-Order Components — Ilya GelmanHigher-Order Components — Ilya Gelman
Higher-Order Components — Ilya Gelman
 
React vs angular
React vs angularReact vs angular
React vs angular
 
D3 svg & angular
D3 svg & angularD3 svg & angular
D3 svg & angular
 
ReactJS vs AngularJS - Head to Head comparison
ReactJS vs AngularJS - Head to Head comparisonReactJS vs AngularJS - Head to Head comparison
ReactJS vs AngularJS - Head to Head comparison
 
Understanding Redux — Ilya Gelman
Understanding Redux — Ilya GelmanUnderstanding Redux — Ilya Gelman
Understanding Redux — Ilya Gelman
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

State managment in a world of hooks

  • 1. State Management in a World of Hooks Maayan Glikser Adam Klein &
  • 5. Hooks let us organize stateful logic inside components into reusable isolated units.
  • 6. How did we share logic between components in the past?
  • 7.
  • 9. Mixins const MouseMixin = { getInitialState() { return { x: 0, y: 0 } }, handleMouseMove(event) { this.setState({ x: event.clientX, y: event.clientY }) } }
  • 10. Mixins const App = React.createClass({ // Use the mixin! mixins: [ MouseMixin ], render() { const { x, y } = this.state return ( <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}> <h1>The mouse position is ({x}, {y})</h1> </div> ) } })
  • 12. Higher Order Component (HoC) function logProps(WrappedComponent) { return class extends React.Component { componentWillReceiveProps(nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); } render() { // Wraps the input component in a container, without mutating it. Good! return <WrappedComponent {...this.props} />; } } }
  • 13. Higher Order Component (HoC) const AppWithLog = logProps(App);
  • 14.
  • 16.
  • 17. Render Props class Mouse extends React.Component { handleMouseMove = (event) => { this.setState({ x: event.clientX, y: event.clientY }) } render() { return ( <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}> {this.props.render(this.state)} </div> ) } }
  • 18. Render Props const App = () => ( <div> <Mouse render={({ x, y }) => ( // The render prop gives us the state we need // to render whatever we want here. <h1>The mouse position is ({x}, {y})</h1> )}/> </div> );
  • 19. const MyForm = () => ( <DataFetcher> {( data ) => ( <Actions> {( actions ) => ( <Translations> {( translations ) => ( <Styles> {(styles) => ( <form style={styles}> <input type="text" value={data.value} /> <button onClick={action.submit}> { translations.submitText } </button> </form> )} </Styles> )} </Translations> )} </Actions> )} </DataFetcher> );
  • 20. Hooks
  • 21. Hooks are stateful small units of logic which are easy to reuse and test.
  • 22. const App = () => { const [user, setRole, ROLES] = useUser(); return ( <div style={{ height: '100%' }}> Welcome { user } <button onClick={() => setRole(ROLES.ADMIN)}> Make Admin </button> </div> ); };
  • 23. const useUser = () => { const ROLES = { ADMIN: 'ADMIN', CLIENT: 'CLIENT' }; const [user, setUser] = useState(null); const setAdmin = useCallback((role) => { setUser({ ...user, role }); }, [user]); return [user, setAdmin, ROLES]; };
  • 24.
  • 25. How do we share data between components?
  • 28. <App /> <User /> UsersProvider Logged In Username UsersConsumer
  • 29. const App = () => ( <Provider> <Provider1> <Provider2> <Provider3> <Provider4> <Provider5> <Layout /> </Provider5> </Provider4> </Provider3> </Provider2> </Provider1> </Provider> );
  • 30. const App = () => ( <Layout> <UsersProvider> <Header /> </UsersProvider> <AccountsProvider> <AccountScreen /> </AccountsProvider> <Footer /> </Layout> );
  • 31. When Context Isn't enough Where do we go from here?
  • 33. <App /> <Layout /> <Header /> <Accounts /> <User /> Store Users Accounts State Managment React Component Tree
  • 36. Moving from Context to State Managment Large refactor
  • 37. What if it could be easier?
  • 38. Developer, Consultant, Trainer CEO @ 500Tech I love dad jokes Adam Klein
  • 39. Thank You Maayan Glikser Adam Klein & https://github.com/adamkleingit/reusable-talk https://github.com/reusablejs/reusable @maayanglikser @adamklein500