SlideShare a Scribd company logo
The road to react hooks
Younes
CopenhagenJS <november>
How do I share (stateful) code between
components ?
Code/Logic share
● Mixins
● Higher order components
● Render props (aka function as child)
● Children composition
Mixins
mixin
const windowResize = {
getInitialState() {
return { width: 0 };
},
handler() {
const {innerWidth: width} = window;
this.setState({ width });
},
componentDidMount() {
window.addEventListener("resize", this.handler);
},
componentWillUnmount() {
window.removeEventListener("resize", this.handler);
}
};
component
const Component = React.createClass({
mixins: [windowResize],
render() {
return this.state.width > 500
? this.props.children
: null;
}
});
Why not mixins ?
● implicit and hard to track dependencies (Indirection)
● name clashes
● snowballing complexity (DEFINE_ONCE, OVERRIDE_BASE ...)
● New ES-6 classes API
higher order components
a function that takes an existing component and
returns another component that wraps it
function withDataLoader(Component) {
return class extends React.Component {
state = { data: null, loading: true }
async componentDidMount() {
const data = await API.get(this.props.url);
this.setState({ data, loading: false });
}
render() {
return <Component data={this.state.data} loading={this.state.loading} />}
}
}
const EnhancedComponent = withDataLoader(MyComponent);
<EnhancedComponent url={url} />
Examples of HOC
● graphql(gql`{ ... }`)(Component);
● connect(mapState, actions)(Component);
● withRouter(Component);
Render props
share code using a prop whose value is a function
class DataLoader extends React.Component {
state = { data: null, loading: true };
async componentDidMount() {
// some caching logic maybe?
const data = await API.get(this.props.url);
this.setState({ data, loading: false });
}
render() {
const { loading, data } = this.state;
return this.props.render({ loading, data });
}
}
<DataLoader
url={url}
render={({ data, loading }) =>
/* some JSX */
}
/>
Examples of Render Props
● Apollo Query/Mutation
● React Router
● react-motion/spring
But!
● a lot of ceremony (HOCs more)
● Wrapper Hell
● classes?
Class Components/Classes ?
Class components ?
● Huge components, hard to reuse logic
● Classes are difficult for humans
● Classes are difficult for machines (transpile, hot reload, Tree
shaking)
Hooks ?
Functions that let you “hook into” React state and lifecycle features from function
components. Hooks don’t work inside classes — they let you use React without
classes
It's a proposal ?
Show me some code !
React relies on the order in which Hooks are called
Persisted Effectsfunction Component() {
const [name, setName] = useState('default');
useEffect(function effect1() { /*code*/ });
const [count, setCounter] = useState(0);
useEffect(function effect2() { /*code*/ });
// return some JSX
}
Current value: “default”
Current Function: ƒ effect1
Current value: 0
Current Function: ƒ effect2
Hooks Rules
● Only call Hooks at the top level (no loops, condition etc..)
● Only from React function components (expect custom Hooks)
● Names should start with use (linting hint)
useContext
function ComponentA() {
const theme = React.useContext(ThemeContext);
// other hooks
// return some jsx
}
useRef
function Focus() {
const inputRef = useRef(null);
const clickHandler = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={clickHandler}>Focus the input</button>
</>
);
}
useReducer
function reducer(state, action) {
switch (action) {
case 'increment': return state.count + 1;
case 'decrement': return state.count - 1;
default: return state;
}
}
function Counter({ initialCount }) {
const [state, dispatch] = useReducer(reducer, initialCount);
return (
<>
Count: {state.count}
<button onClick={() => dispatch('increment')}>+</button>
<button onClick={() => dispatch('decrement')}>-</button>
</>
);
}
Custom hooks
function FriendStatus({ friendId }) {
const { match, history } = useRouter();
const state = useConnect(mapState);
const { data, loading } = Apollo.useQuery(QUERY);
// return some jsx
}
Custom hooks by community
function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
useEffect(() => {
ChatAPI.subscribeToFriendStatus(friendID,
handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(friendID,
handleStatusChange);
};
});
return isOnline;
}
function FriendStatus({ friendId }) {
const isOnline = useFriendStatus(friendId);
return isOnline ? 'Online' : 'Offline';
}
Custom hooks
React.PureComponent ?
React.memo HOC (aka Pure)
import React from "react";
const MyComponent = ({ props1, props2 }) => {
// return some JSX
};
export default React.memo(MyComponent, customEqual?);
This is all ?
Nop, Suspense
(async/concurrent React)
1. before render() method, try to read a value from the cache.
2. If the value is already in the cache, the render continues
3. If the value is not already in the cache, throws the promise as an error
4. When the promise resolves, React continues from where it stopped
Suspense
Suspense
....
<ErrorBoundry>
<Suspense fallback={Loader}>
<ComponentA>
<AsyncDataComponent />
</ComponentA>
</Suspense>
</ErrorBoundry>
....
● Class components are not dead
● But there is a lot of benefits of using Hooks
● A beautiful future is ahead (concurrent mode, suspense)
Thank you!
_younesmln

More Related Content

What's hot

rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
Alexander Mostovenko
 

What's hot (19)

Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 
Redux + RxJS + Ember makes simple
Redux + RxJS + Ember makes simpleRedux + RxJS + Ember makes simple
Redux + RxJS + Ember makes simple
 
Hands On React
Hands On React Hands On React
Hands On React
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Matreshka.js
Matreshka.jsMatreshka.js
Matreshka.js
 
Matreshka.js
Matreshka.jsMatreshka.js
Matreshka.js
 
Add Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJSAdd Some Fun to Your Functional Programming With RXJS
Add Some Fun to Your Functional Programming With RXJS
 
Deferred
DeferredDeferred
Deferred
 
React.js workshop by tech47.in
React.js workshop by tech47.inReact.js workshop by tech47.in
React.js workshop by tech47.in
 
Reactивная тяга
Reactивная тягаReactивная тяга
Reactивная тяга
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Using Change Streams to Keep Up with Your Data
Using Change Streams to Keep Up with Your DataUsing Change Streams to Keep Up with Your Data
Using Change Streams to Keep Up with Your Data
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
Uni2
Uni2Uni2
Uni2
 
Visual Studio.Net - Sql Server
Visual Studio.Net - Sql ServerVisual Studio.Net - Sql Server
Visual Studio.Net - Sql Server
 
Understanding redux
Understanding reduxUnderstanding redux
Understanding redux
 
Map kit light
Map kit lightMap kit light
Map kit light
 

Similar to Road to react hooks

Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer Simsek
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 

Similar to Road to react hooks (20)

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
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react application
 
React hooks
React hooksReact hooks
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!
 
React lecture
React lectureReact lecture
React lecture
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creators
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 
React redux
React reduxReact redux
React redux
 
N Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React NativeN Things You Don't Want to Repeat in React Native
N Things You Don't Want to Repeat in React Native
 
React/Redux
React/ReduxReact/Redux
React/Redux
 
React 101
React 101React 101
React 101
 
How do we use hooks
How do we use hooksHow do we use hooks
How do we use hooks
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order component
 
Strategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux ApplicaitonsStrategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux Applicaitons
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 

Recently uploaded

Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
Kamal Acharya
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
Atif Razi
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
Kamal Acharya
 

Recently uploaded (20)

A case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfA case study of cinema management system project report..pdf
A case study of cinema management system project report..pdf
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering Workshop
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Introduction to Casting Processes in Manufacturing
Introduction to Casting Processes in ManufacturingIntroduction to Casting Processes in Manufacturing
Introduction to Casting Processes in Manufacturing
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptx
 
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
 
Danfoss NeoCharge Technology -A Revolution in 2024.pdf
Danfoss NeoCharge Technology -A Revolution in 2024.pdfDanfoss NeoCharge Technology -A Revolution in 2024.pdf
Danfoss NeoCharge Technology -A Revolution in 2024.pdf
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
NO1 Pandit Amil Baba In Bahawalpur, Sargodha, Sialkot, Sheikhupura, Rahim Yar...
 
Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.Quality defects in TMT Bars, Possible causes and Potential Solutions.
Quality defects in TMT Bars, Possible causes and Potential Solutions.
 
Toll tax management system project report..pdf
Toll tax management system project report..pdfToll tax management system project report..pdf
Toll tax management system project report..pdf
 

Road to react hooks

  • 1. The road to react hooks Younes CopenhagenJS <november>
  • 2. How do I share (stateful) code between components ?
  • 3. Code/Logic share ● Mixins ● Higher order components ● Render props (aka function as child) ● Children composition
  • 5. mixin const windowResize = { getInitialState() { return { width: 0 }; }, handler() { const {innerWidth: width} = window; this.setState({ width }); }, componentDidMount() { window.addEventListener("resize", this.handler); }, componentWillUnmount() { window.removeEventListener("resize", this.handler); } }; component const Component = React.createClass({ mixins: [windowResize], render() { return this.state.width > 500 ? this.props.children : null; } });
  • 6.
  • 7. Why not mixins ? ● implicit and hard to track dependencies (Indirection) ● name clashes ● snowballing complexity (DEFINE_ONCE, OVERRIDE_BASE ...) ● New ES-6 classes API
  • 8.
  • 9. higher order components a function that takes an existing component and returns another component that wraps it
  • 10. function withDataLoader(Component) { return class extends React.Component { state = { data: null, loading: true } async componentDidMount() { const data = await API.get(this.props.url); this.setState({ data, loading: false }); } render() { return <Component data={this.state.data} loading={this.state.loading} />} } } const EnhancedComponent = withDataLoader(MyComponent); <EnhancedComponent url={url} />
  • 11. Examples of HOC ● graphql(gql`{ ... }`)(Component); ● connect(mapState, actions)(Component); ● withRouter(Component);
  • 12.
  • 13. Render props share code using a prop whose value is a function
  • 14. class DataLoader extends React.Component { state = { data: null, loading: true }; async componentDidMount() { // some caching logic maybe? const data = await API.get(this.props.url); this.setState({ data, loading: false }); } render() { const { loading, data } = this.state; return this.props.render({ loading, data }); } } <DataLoader url={url} render={({ data, loading }) => /* some JSX */ } />
  • 15. Examples of Render Props ● Apollo Query/Mutation ● React Router ● react-motion/spring
  • 16. But! ● a lot of ceremony (HOCs more) ● Wrapper Hell ● classes?
  • 18. Class components ? ● Huge components, hard to reuse logic ● Classes are difficult for humans ● Classes are difficult for machines (transpile, hot reload, Tree shaking)
  • 19. Hooks ? Functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes
  • 21. Show me some code !
  • 22. React relies on the order in which Hooks are called Persisted Effectsfunction Component() { const [name, setName] = useState('default'); useEffect(function effect1() { /*code*/ }); const [count, setCounter] = useState(0); useEffect(function effect2() { /*code*/ }); // return some JSX } Current value: “default” Current Function: ƒ effect1 Current value: 0 Current Function: ƒ effect2
  • 23. Hooks Rules ● Only call Hooks at the top level (no loops, condition etc..) ● Only from React function components (expect custom Hooks) ● Names should start with use (linting hint)
  • 24. useContext function ComponentA() { const theme = React.useContext(ThemeContext); // other hooks // return some jsx }
  • 25. useRef function Focus() { const inputRef = useRef(null); const clickHandler = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} type="text" /> <button onClick={clickHandler}>Focus the input</button> </> ); }
  • 26. useReducer function reducer(state, action) { switch (action) { case 'increment': return state.count + 1; case 'decrement': return state.count - 1; default: return state; } } function Counter({ initialCount }) { const [state, dispatch] = useReducer(reducer, initialCount); return ( <> Count: {state.count} <button onClick={() => dispatch('increment')}>+</button> <button onClick={() => dispatch('decrement')}>-</button> </> ); }
  • 28. function FriendStatus({ friendId }) { const { match, history } = useRouter(); const state = useConnect(mapState); const { data, loading } = Apollo.useQuery(QUERY); // return some jsx } Custom hooks by community
  • 29. function useFriendStatus(friendID) { const [isOnline, setIsOnline] = useState(null); function handleStatusChange(status) { setIsOnline(status.isOnline); } useEffect(() => { ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange); }; }); return isOnline; } function FriendStatus({ friendId }) { const isOnline = useFriendStatus(friendId); return isOnline ? 'Online' : 'Offline'; } Custom hooks
  • 31. React.memo HOC (aka Pure) import React from "react"; const MyComponent = ({ props1, props2 }) => { // return some JSX }; export default React.memo(MyComponent, customEqual?);
  • 32. This is all ? Nop, Suspense (async/concurrent React)
  • 33.
  • 34. 1. before render() method, try to read a value from the cache. 2. If the value is already in the cache, the render continues 3. If the value is not already in the cache, throws the promise as an error 4. When the promise resolves, React continues from where it stopped Suspense
  • 36. ● Class components are not dead ● But there is a lot of benefits of using Hooks ● A beautiful future is ahead (concurrent mode, suspense)