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;
}
});
Road to react hooks
Why not mixins ?
● implicit and hard to track dependencies (Indirection)
● name clashes
● snowballing complexity (DEFINE_ONCE, OVERRIDE_BASE ...)
● New ES-6 classes API
Road to react hooks
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);
Road to react hooks
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)
Road to react hooks
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 (19)

PDF
Cycle.js: Functional and Reactive
Eugene Zharkov
 
PPTX
Redux + RxJS + Ember makes simple
Justin Park
 
PPTX
Hands On React
Abhijit Sinha
 
PDF
Elm: give it a try
Eugene Zharkov
 
PPTX
Matreshka.js
Игорь Якименко
 
PDF
Add Some Fun to Your Functional Programming With RXJS
Ryan Anklam
 
PDF
Deferred
daiying-zhang
 
PDF
React.js workshop by tech47.in
Jaikant Kumaran
 
PDF
Reactивная тяга
Vitebsk Miniq
 
KEY
Object-Oriented Javascript
kvangork
 
PDF
Compose Async with RxJS
Kyung Yeol Kim
 
PDF
jQuery secrets
Bastian Feder
 
PPTX
Using Change Streams to Keep Up with Your Data
Evan Rodd
 
PDF
rx.js make async programming simpler
Alexander Mostovenko
 
TXT
Uni2
miriamfacio
 
PDF
Visual Studio.Net - Sql Server
Darwin Durand
 
PDF
Understanding redux
David Atchley
 
PDF
Map kit light
CocoaHeads France
 
Cycle.js: Functional and Reactive
Eugene Zharkov
 
Redux + RxJS + Ember makes simple
Justin Park
 
Hands On React
Abhijit Sinha
 
Elm: give it a try
Eugene Zharkov
 
Add Some Fun to Your Functional Programming With RXJS
Ryan Anklam
 
Deferred
daiying-zhang
 
React.js workshop by tech47.in
Jaikant Kumaran
 
Reactивная тяга
Vitebsk Miniq
 
Object-Oriented Javascript
kvangork
 
Compose Async with RxJS
Kyung Yeol Kim
 
jQuery secrets
Bastian Feder
 
Using Change Streams to Keep Up with Your Data
Evan Rodd
 
rx.js make async programming simpler
Alexander Mostovenko
 
Visual Studio.Net - Sql Server
Darwin Durand
 
Understanding redux
David Atchley
 
Map kit light
CocoaHeads France
 

Similar to Road to react hooks (20)

PPTX
React hooks
Ramy ElBasyouni
 
PDF
Understanding react hooks
Samundra khatri
 
PDF
How do we use hooks
Jim Liu
 
PDF
React Back to the Future
500Tech
 
PDF
React new features and intro to Hooks
Soluto
 
PPTX
Green Custard Friday Talk 21: React Hooks
Green Custard
 
PDF
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JSFestUA
 
PDF
React JS Hooks Sheet .pdf
nishant078cs23
 
PDF
Important React Hooks
Knoldus Inc.
 
PDF
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
PDF
Understanding React hooks | Walkingtree Technologies
Walking Tree Technologies
 
PPTX
React hooks
Assaf Gannon
 
PDF
React – Let’s “Hook” up
InnovationM
 
PDF
How to build a react native app with the help of react native hooks
Katy Slemon
 
PDF
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
PPTX
Understanding react hooks
Maulik Shah
 
PPTX
React workshop
Imran Sayed
 
PPTX
React Hooks
Erez Cohen
 
PDF
100 React Interview questions 2024.pptx.pdf
codevincent624
 
PPTX
React-JS.pptx
AnmolPandita7
 
React hooks
Ramy ElBasyouni
 
Understanding react hooks
Samundra khatri
 
How do we use hooks
Jim Liu
 
React Back to the Future
500Tech
 
React new features and intro to Hooks
Soluto
 
Green Custard Friday Talk 21: React Hooks
Green Custard
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JSFestUA
 
React JS Hooks Sheet .pdf
nishant078cs23
 
Important React Hooks
Knoldus Inc.
 
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
Understanding React hooks | Walkingtree Technologies
Walking Tree Technologies
 
React hooks
Assaf Gannon
 
React – Let’s “Hook” up
InnovationM
 
How to build a react native app with the help of react native hooks
Katy Slemon
 
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
Understanding react hooks
Maulik Shah
 
React workshop
Imran Sayed
 
React Hooks
Erez Cohen
 
100 React Interview questions 2024.pptx.pdf
codevincent624
 
React-JS.pptx
AnmolPandita7
 
Ad

Recently uploaded (20)

PDF
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Machine Learning All topics Covers In This Single Slides
AmritTiwari19
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
PPTX
Online Cab Booking and Management System.pptx
diptipaneri80
 
PPTX
Precedence and Associativity in C prog. language
Mahendra Dheer
 
PDF
SG1-ALM-MS-EL-30-0008 (00) MS - Isolators and disconnecting switches.pdf
djiceramil
 
PPTX
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
PPTX
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
PPTX
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Machine Learning All topics Covers In This Single Slides
AmritTiwari19
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
Online Cab Booking and Management System.pptx
diptipaneri80
 
Precedence and Associativity in C prog. language
Mahendra Dheer
 
SG1-ALM-MS-EL-30-0008 (00) MS - Isolators and disconnecting switches.pdf
djiceramil
 
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
filteration _ pre.pptx 11111110001.pptx
awasthivaibhav825
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
Ad

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; } });
  • 7. Why not mixins ? ● implicit and hard to track dependencies (Indirection) ● name clashes ● snowballing complexity (DEFINE_ONCE, OVERRIDE_BASE ...) ● New ES-6 classes API
  • 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);
  • 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)
  • 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)