SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler offline
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

Mais conteúdo relacionado

Semelhante a State managment in a world of 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!JSFestUA
 
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 usOSCON Byrum
 
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 componentKaty Slemon
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creatorsGeorge Bukhanov
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"GeeksLab Odessa
 
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 WindowsPhoneMohammad Shaker
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to ReactJean Carlo Emer
 
Advanced React Component Patterns - ReactNext 2018
Advanced React Component Patterns - ReactNext 2018Advanced React Component Patterns - ReactNext 2018
Advanced React Component Patterns - ReactNext 2018Robert Herbst
 
Stay with React.js in 2020
Stay with React.js in 2020Stay with React.js in 2020
Stay with React.js in 2020Jerry Liao
 
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 WireAndreas Nedbal
 
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 ReactJonne Kats
 
Introduction to React and MobX
Introduction to React and MobXIntroduction to React and MobX
Introduction to React and MobXAnjali Chawla
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
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 scenesBinary Studio
 
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-1Augustin Bralley
 

Semelhante a 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
 

Mais de 500Tech

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 2019500Tech
 
React Back to the Future
React Back to the FutureReact Back to the Future
React Back to the Future500Tech
 
Hooks - why should you care today?
Hooks - why should you care today?Hooks - why should you care today?
Hooks - why should you care today?500Tech
 
Migrating from angular to react
Migrating from angular to reactMigrating from angular to react
Migrating from angular to react500Tech
 
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)500Tech
 
Opinionated Approach to Redux
Opinionated Approach to ReduxOpinionated Approach to Redux
Opinionated Approach to Redux500Tech
 
Mobx Internals
Mobx InternalsMobx Internals
Mobx Internals500Tech
 
Mobx - Performance and Sanity
Mobx - Performance and SanityMobx - Performance and Sanity
Mobx - Performance and Sanity500Tech
 
Mobx Performance and Sanity
Mobx Performance and SanityMobx Performance and Sanity
Mobx Performance and Sanity500Tech
 
Mobx - performance and sanity
Mobx - performance and sanityMobx - performance and sanity
Mobx - performance and sanity500Tech
 
Tales of an open source library
Tales of an open source libraryTales of an open source library
Tales of an open source library500Tech
 
Angular2 a modern web platform
Angular2   a modern web platformAngular2   a modern web platform
Angular2 a modern web platform500Tech
 
Angular. MobX. Happiness
Angular. MobX. HappinessAngular. MobX. Happiness
Angular. MobX. Happiness500Tech
 
Render to DOM
Render to DOMRender to DOM
Render to DOM500Tech
 
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 Redux500Tech
 
Higher-Order Components — Ilya Gelman
Higher-Order Components — Ilya GelmanHigher-Order Components — Ilya Gelman
Higher-Order Components — Ilya Gelman500Tech
 
React vs angular
React vs angularReact vs angular
React vs angular500Tech
 
D3 svg & angular
D3 svg & angularD3 svg & angular
D3 svg & angular500Tech
 
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 comparison500Tech
 
Understanding Redux — Ilya Gelman
Understanding Redux — Ilya GelmanUnderstanding Redux — Ilya Gelman
Understanding Redux — Ilya Gelman500Tech
 

Mais de 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
 

Último

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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.pdfsudhanshuwaghmare1
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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 productivityPrincipled Technologies
 

Último (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 

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