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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

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

Ähnlich wie 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
洪 鹏发
 

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

Kürzlich hochgeladen

VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 

Kürzlich hochgeladen (20)

University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 

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)