SlideShare a Scribd company logo
With great power comes
great React Hooks!
Glenn Reyes
@glnnrys
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
Glenn Reyes
👪 🎸 🌎
Freelance JavaScript Engineer
@glnnrys
Let's talk
components!
var App = React.createClass({
getInitialState: function() {
return { value: '' };
},
onChange: function(event) {
this.setState({ value: event.target.value });
},
render: function() {
return (
<div>
<input type="text" value={this.state.value} onChange={this.onChange} />
<p>{this.state.value}</p>
</div>
);
},
});
[GIF?]
React.createClass({
mixins: [ReactWindowMixins.OnResize],
render: function() {
const { window } = this.state;
return (
<div>
current window size: {window.width}, {window.height}
</div>
);
}
});
React.createClass({
mixins: [ReactWindowMixins.OnResize], // 🤦🤦🤦🤦🤦🤦🤦
render: function() {
const { window } = this.state;
return (
<div>
current window size: {window.width}, {window.he
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
class App extends React.Component {
state = { value: '' };
onChange = event => {
this.setState({ value: event.target.value });
}
render() {
return (
<div>
<input type="text" value={this.state.value} onChange={this.onChange} />
<p>{this.state.value}</p>
</div>
)
}
}
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
const App = (props) => {
const greeting = 'Hello';
return <div>{greeting} {props.name}!</div>;
}
How do I add state to
function components?
Container & Presentational
Components
Container & Presentational
Components
DATA UI
class MyData extends React.Component {
state = { value: '' };
onChange = event => {
this.setState({ value: event.target.value });
}
render() {
return (
<MyUI value={this.state.value} onChange={this.onChange} />
)
}
}
const MyUI = ({ value, onChange }) => (
<div>
<input type="text" value={value} onChange={onChange} />
<p>{value}</p>
</div>
)
class MyData extends React.Component {
state = { value: '' };
onChange = event => {
this.setState({ value: event.target.value });
}
render() {
return (
<MyUI value={this.state.value} onChange={this.onChange} />
)
}
}
const MyUI = ({ value, onChange }) => (
<div>
<input type="text" value={value} onChange={onChange} />
<p>{value}</p>
</div>
)
class MyData extends React.Component {
state = { value: '' };
onChange = event => {
this.setState({ value: event.target.value });
}
render() {
return (
<MyUI value={this.state.value} onChange={this.onChange} />
)
}
}
Higher Order Components!
const EnhancedComponent = higherOrderComponent(WrappedComponent);
const withInput = Component => class InputContainer extends React.Component {
state = { value: '' };
onChange = event => {
this.setState({ value: event.target.value });
}
render() {
return (
<Component value={this.state.value} onChange={this.onChange} />
)
}
}
const App = withInput(({ value, onChange }) => (
<div>
<input type="text" value={value} onChange={onChange} />
<p>{value}</p>
</div>
))
hoc1(hoc2(hoc3(hoc4(Component))))
compose(
hoc1,
hoc2,
hoc3,
hoc4
)(Component)
Thank god Render Props
came around!
class DataProvider extends React.Component {
state = { data: null }
componentDidMount() {
fetchSomeData().then(data => this.setState({ data }));
}
render() {
return this.props.render(data);
}
}
<DataProvider render={data => (
<h1>Hello {data.name}</h1>
)}/>
class DataProvider extends React.Component {
state = { data: null }
componentDidMount() {
fetchSomeData().then(data => this.setState({ data }));
}
render() {
return this.props.render(data);
}
}
<DataProvider render={data => (
<h1>Hello {data.name}</h1>
)}/>
class DataProvider extends React.Component {
state = { data: null }
componentDidMount() {
fetchSomeData().then(data => this.setState({ data }));
}
render() {
return this.props.render(data);
}
}









class DataProvider extends React.Component {
state = { data: null }
componentDidMount() {
fetchSomeData().then(data => this.setState({ data }));
}
render() {
return this.props.render(data);
}
}
<DataProvider render={data => (
<h1>Hello {data.name}</h1>
)}/>














return this.props.render(data);













class DataProvider extends React.Component {
state = { data: null }
componentDidMount() {
fetchSomeData().then(data => this.setState({ data }));
}
render() {
return this.props.render(data);
}
}
<DataProvider render={data => (
<h1>Hello {data.name}</h1>
)}/>
























<DataProvider render={data => (
<h1>Hello {data.name}</h1>
)}/>
class DataProvider extends React.Component {
state = { data: null }
componentDidMount() {
fetchSomeData().then(data => this.setState({ data }));
}
render() {
return this.props.render(data);
}
}
<DataProvider render={data => (
<h1>Hello {data.name}</h1>
)}/>
























data => (
<h1>Hello {data.name}</h1>
)
class DataProvider extends React.Component {
state = { data: null }
componentDidMount() {
fetchSomeData().then(data => this.setState({ data }));
}
render() {
return this.props.children(data);
}
}
<DataProvider>
{data => (
<h1>Hello {data.name}</h1>
)}
</DataProvider>
https://medium.com/@jackyef/react-hooks-why-we-should-embrace-it-86e408663ad6
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
Hooks! 🎉
What are React Hooks?
Hooks let you use state and other
React features

without writing a class!
Hooks let you use state and other
React features

with just function components!
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
✅ New feature as of React 16.8
✅ Completely opt-in
✅ No breaking changes
✅ Fully backwards compatible
Why React Hooks?
Better reuse and
primitive for stateful logic
between components
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
class FriendStatusWithCounter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0, isOnline: null };
this.handleStatusChange = this.handleStatusChange.bind(this);
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
ChatAPI.subscribeToFriendStatus(
this.props.friend.id,
this.handleStatusChange
);
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
componentWillUnmount() {
ChatAPI.unsubscribeFromFriendStatus(
this.props.friend.id,
this.handleStatusChange
);
}
handleStatusChange(status) {
this.setState({
isOnline: status.isOnline
});
}
// ...
function FriendStatusWithCounter(props) {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
// ...
}
Hooks lets us organize logic
into reusable isolated units
No more wrapper hell
DEMO TIME!
What will happen to React classes?
Nothing.
How will hooks affect the
core concepts of React?
✅ Everything you already know won't change
✅ Hooks provide a more direct API
👉 props
👉 state
👉 context
👉 refs
👉 lifecycle
😄 No more constructor
😄 No more bindings
😄 No more this
😄 Less code
😄 Cleaner code
😓 Learning curve
😓 Bigger React API surface
😓 Not all covered (yet)
😓 There are some rules
☝ Only from React functions
☝ Only on top level
Hooks rely on call order.
function Form() {
// 1. Use the name state variable
const [name, setName] = useState('Mary');
// 2. Use an effect for persisting the form
useEffect(function persistForm() {
localStorage.setItem('formData', name);
});
// 3. Use the surname state variable
const [surname, setSurname] = useState('Poppins');
// 4. Use an effect for updating the title
useEffect(function updateTitle() {
document.title = name + ' ' + surname;
});
// ...
}
// ------------
// First render
// ------------
useState('Mary') // 1. Initialize name state variable with 'Mary'
useEffect(persistForm) // 2. Add an effect for persisting the form
useState('Poppins') // 3. Initialize surname state variable
useEffect(updateTitle) // 4. Add an effect for updating the title
// -------------
// Second render
// -------------
useState('Mary') // 1. Read name state variable (argument ignored)
useEffect(persistForm) // 2. Replace the effect for persisting the form
useState('Poppins') // 3. Read surname state variable (argument ignored)
useEffect(updateTitle) // 4. Replace the effect for updating the title
// ...
// 🔴 We're breaking the rule by using a Hook in a condition
if (name !== '') {
useEffect(function persistForm() {
localStorage.setItem('formData', name);
});
}
useState('Mary') // 1. Read name state variable (argument ignored)
// useEffect(persistForm) // 🔴 This Hook was skipped!
useState('Poppins') // 🔴 2 (but was 3). Fail to read the surname state
useEffect(updateTitle) // 🔴 3 (but was 4). Fail to replace the effect
useEffect(function persistForm() {
// 👍 We're not breaking the first rule anymore
if (name !== '') {
localStorage.setItem('formData', name);
}
});
When to useReducer over 
useState?
Start with useState when
building new components
Switch to useReducer on
larger state shapes
How about tooling?
eslint-plugin-react-hooks
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
How to do I test
React Hooks?
You don't.
Test the component
as usual.
@glnnrys
🔗 reactjs.org/hooks
🔗 nikgraf.github.io/react-hooks
🔗 github.com/rehooks/awesome-react-hooks
🔗 codesandbox.io/s/github/glennreyes/hooks-demo
Glenn Reyes
@glnnrys
Thank you!
🔗 reactjs.org/hooks
🔗 nikgraf.github.io/react-hooks
🔗 github.com/rehooks/awesome-react-hooks
🔗 codesandbox.io/s/github/glennreyes/hooks-demo

More Related Content

PPTX
Indeed My Jobs: A case study in ReactJS and Redux (Meetup talk March 2016)
PDF
Stay with React.js in 2020
PDF
Intro to React | DreamLab Academy
PDF
How to Mess Up Your Angular UI Components
PDF
Extending Redux in the Server Side
PDF
React Performance
PDF
Egghead redux-cheat-sheet-3-2-1
PDF
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them
Indeed My Jobs: A case study in ReactJS and Redux (Meetup talk March 2016)
Stay with React.js in 2020
Intro to React | DreamLab Academy
How to Mess Up Your Angular UI Components
Extending Redux in the Server Side
React Performance
Egghead redux-cheat-sheet-3-2-1
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them

What's hot (19)

PDF
Advanced Akka For Architects
KEY
Sexy.js: A Sequential Ajax (Sajax) library for jQuery
DOCX
Michael Colon Portfolio
PDF
React.js workshop by tech47.in
DOC
Converting Db Schema Into Uml Classes
PDF
Android crashcourse
PDF
Windows 8 Training Fundamental - 1
PDF
Simplified Android Development with Simple-Stack
PPTX
DroidKnight 2018 State machine by Selaed class
PDF
Understanding redux
PDF
SQL Stored Procedures For My Library Project
PDF
Reactive programming in clojure script using reactjs wrappers
PDF
Androidppt 1
PDF
Crossing platforms with JavaScript & React
PPTX
Paging Like A Pro
PDF
Matteo Antony Mistretta - Refactoring into React hooks - Codemotion Rome 2019
PDF
DRUPAL 8 STORAGES OVERVIEW
PDF
2018 02-22 React, Redux & Building Applications that Scale | Redux
PDF
SQLite in Adobe AIR
Advanced Akka For Architects
Sexy.js: A Sequential Ajax (Sajax) library for jQuery
Michael Colon Portfolio
React.js workshop by tech47.in
Converting Db Schema Into Uml Classes
Android crashcourse
Windows 8 Training Fundamental - 1
Simplified Android Development with Simple-Stack
DroidKnight 2018 State machine by Selaed class
Understanding redux
SQL Stored Procedures For My Library Project
Reactive programming in clojure script using reactjs wrappers
Androidppt 1
Crossing platforms with JavaScript & React
Paging Like A Pro
Matteo Antony Mistretta - Refactoring into React hooks - Codemotion Rome 2019
DRUPAL 8 STORAGES OVERVIEW
2018 02-22 React, Redux & Building Applications that Scale | Redux
SQLite in Adobe AIR
Ad

Similar to JS Fest 2019. Glenn Reyes. With great power comes great React hooks! (20)

PDF
React Back to the Future
PDF
React new features and intro to Hooks
PDF
React JS Hooks Sheet .pdf
PPTX
React hooks
PPTX
React Hooks Best Practices in 2022.pptx
PDF
React lecture
PDF
Road to react hooks
PDF
React – Let’s “Hook” up
PDF
React for Dummies
PDF
Integrating React.js with PHP projects
PDF
react-hooks.pdf
PDF
React & The Art of Managing Complexity
PDF
Workshop 19: ReactJS Introduction
PDF
Quick start with React | DreamLab Academy #2
PDF
Understanding react hooks
PDF
2018 05-16 Evolving Technologies: React, Babel & Webpack
PDF
How to build a react native app with the help of react native hooks
PDF
Understanding React hooks | Walkingtree Technologies
PDF
Enhance react app with patterns - part 1: higher order component
PDF
Strategies for Mitigating Complexity in React Based Redux Applicaitons
React Back to the Future
React new features and intro to Hooks
React JS Hooks Sheet .pdf
React hooks
React Hooks Best Practices in 2022.pptx
React lecture
Road to react hooks
React – Let’s “Hook” up
React for Dummies
Integrating React.js with PHP projects
react-hooks.pdf
React & The Art of Managing Complexity
Workshop 19: ReactJS Introduction
Quick start with React | DreamLab Academy #2
Understanding react hooks
2018 05-16 Evolving Technologies: React, Babel & Webpack
How to build a react native app with the help of react native hooks
Understanding React hooks | Walkingtree Technologies
Enhance react app with patterns - part 1: higher order component
Strategies for Mitigating Complexity in React Based Redux Applicaitons
Ad

More from JSFestUA (20)

PDF
JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
PDF
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
PDF
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
PDF
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
PDF
JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Dat...
PDF
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
PPTX
JS Fest 2019/Autumn. Александр Товмач. JAMstack
PPTX
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
PPTX
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
PPTX
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
PPTX
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
PPTX
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?
PPTX
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
PDF
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
PPTX
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
PDF
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
PDF
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
PPTX
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
PPTX
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
PPTX
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Dat...
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
JS Fest 2019/Autumn. Александр Товмач. JAMstack
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...

Recently uploaded (20)

PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
Cell Structure & Organelles in detailed.
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
Lesson notes of climatology university.
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Trump Administration's workforce development strategy
PDF
Updated Idioms and Phrasal Verbs in English subject
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
A systematic review of self-coping strategies used by university students to ...
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Final Presentation General Medicine 03-08-2024.pptx
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Chinmaya Tiranga quiz Grand Finale.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Yogi Goddess Pres Conference Studio Updates
Cell Structure & Organelles in detailed.
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Lesson notes of climatology university.
Final Presentation General Medicine 03-08-2024.pptx
Weekly quiz Compilation Jan -July 25.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Trump Administration's workforce development strategy
Updated Idioms and Phrasal Verbs in English subject
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
What if we spent less time fighting change, and more time building what’s rig...
STATICS OF THE RIGID BODIES Hibbelers.pdf

JS Fest 2019. Glenn Reyes. With great power comes great React hooks!

  • 1. With great power comes great React Hooks! Glenn Reyes @glnnrys
  • 4. Glenn Reyes 👪 🎸 🌎 Freelance JavaScript Engineer @glnnrys
  • 6. var App = React.createClass({ getInitialState: function() { return { value: '' }; }, onChange: function(event) { this.setState({ value: event.target.value }); }, render: function() { return ( <div> <input type="text" value={this.state.value} onChange={this.onChange} /> <p>{this.state.value}</p> </div> ); }, });
  • 8. React.createClass({ mixins: [ReactWindowMixins.OnResize], render: function() { const { window } = this.state; return ( <div> current window size: {window.width}, {window.height} </div> ); } });
  • 9. React.createClass({ mixins: [ReactWindowMixins.OnResize], // 🤦🤦🤦🤦🤦🤦🤦 render: function() { const { window } = this.state; return ( <div> current window size: {window.width}, {window.he
  • 12. class App extends React.Component { state = { value: '' }; onChange = event => { this.setState({ value: event.target.value }); } render() { return ( <div> <input type="text" value={this.state.value} onChange={this.onChange} /> <p>{this.state.value}</p> </div> ) } }
  • 14. const App = (props) => { const greeting = 'Hello'; return <div>{greeting} {props.name}!</div>; }
  • 15. How do I add state to function components?
  • 18. class MyData extends React.Component { state = { value: '' }; onChange = event => { this.setState({ value: event.target.value }); } render() { return ( <MyUI value={this.state.value} onChange={this.onChange} /> ) } } const MyUI = ({ value, onChange }) => ( <div> <input type="text" value={value} onChange={onChange} /> <p>{value}</p> </div> )
  • 19. class MyData extends React.Component { state = { value: '' }; onChange = event => { this.setState({ value: event.target.value }); } render() { return ( <MyUI value={this.state.value} onChange={this.onChange} /> ) } } const MyUI = ({ value, onChange }) => ( <div> <input type="text" value={value} onChange={onChange} /> <p>{value}</p> </div> ) class MyData extends React.Component { state = { value: '' }; onChange = event => { this.setState({ value: event.target.value }); } render() { return ( <MyUI value={this.state.value} onChange={this.onChange} /> ) } }
  • 21. const EnhancedComponent = higherOrderComponent(WrappedComponent);
  • 22. const withInput = Component => class InputContainer extends React.Component { state = { value: '' }; onChange = event => { this.setState({ value: event.target.value }); } render() { return ( <Component value={this.state.value} onChange={this.onChange} /> ) } } const App = withInput(({ value, onChange }) => ( <div> <input type="text" value={value} onChange={onChange} /> <p>{value}</p> </div> ))
  • 25. Thank god Render Props came around!
  • 26. class DataProvider extends React.Component { state = { data: null } componentDidMount() { fetchSomeData().then(data => this.setState({ data })); } render() { return this.props.render(data); } } <DataProvider render={data => ( <h1>Hello {data.name}</h1> )}/>
  • 27. class DataProvider extends React.Component { state = { data: null } componentDidMount() { fetchSomeData().then(data => this.setState({ data })); } render() { return this.props.render(data); } } <DataProvider render={data => ( <h1>Hello {data.name}</h1> )}/> class DataProvider extends React.Component { state = { data: null } componentDidMount() { fetchSomeData().then(data => this.setState({ data })); } render() { return this.props.render(data); } }
 
 
 
 

  • 28. class DataProvider extends React.Component { state = { data: null } componentDidMount() { fetchSomeData().then(data => this.setState({ data })); } render() { return this.props.render(data); } } <DataProvider render={data => ( <h1>Hello {data.name}</h1> )}/> 
 
 
 
 
 
 
 return this.props.render(data);
 
 
 
 
 
 

  • 29. class DataProvider extends React.Component { state = { data: null } componentDidMount() { fetchSomeData().then(data => this.setState({ data })); } render() { return this.props.render(data); } } <DataProvider render={data => ( <h1>Hello {data.name}</h1> )}/> 
 
 
 
 
 
 
 
 
 
 
 
 <DataProvider render={data => ( <h1>Hello {data.name}</h1> )}/>
  • 30. class DataProvider extends React.Component { state = { data: null } componentDidMount() { fetchSomeData().then(data => this.setState({ data })); } render() { return this.props.render(data); } } <DataProvider render={data => ( <h1>Hello {data.name}</h1> )}/> 
 
 
 
 
 
 
 
 
 
 
 
 data => ( <h1>Hello {data.name}</h1> )
  • 31. class DataProvider extends React.Component { state = { data: null } componentDidMount() { fetchSomeData().then(data => this.setState({ data })); } render() { return this.props.children(data); } } <DataProvider> {data => ( <h1>Hello {data.name}</h1> )} </DataProvider>
  • 35. What are React Hooks?
  • 36. Hooks let you use state and other React features
 without writing a class!
  • 37. Hooks let you use state and other React features
 with just function components!
  • 38. import React, { useState } from 'react'; function Example() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
  • 39. ✅ New feature as of React 16.8 ✅ Completely opt-in ✅ No breaking changes ✅ Fully backwards compatible
  • 41. Better reuse and primitive for stateful logic between components
  • 42. class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } componentDidMount() { document.title = `You clicked ${this.state.count} times`; } componentDidUpdate() { document.title = `You clicked ${this.state.count} times`; } render() { return ( <div> <p>You clicked {this.state.count} times</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button> </div> ); } }
  • 43. class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } componentDidMount() { document.title = `You clicked ${this.state.count} times`; } componentDidUpdate() { document.title = `You clicked ${this.state.count} times`; } render() { return ( <div> <p>You clicked {this.state.count} times</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button> </div> ); } }
  • 44. function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
  • 45. class FriendStatusWithCounter extends React.Component { constructor(props) { super(props); this.state = { count: 0, isOnline: null }; this.handleStatusChange = this.handleStatusChange.bind(this); } componentDidMount() { document.title = `You clicked ${this.state.count} times`; ChatAPI.subscribeToFriendStatus( this.props.friend.id, this.handleStatusChange ); } componentDidUpdate() { document.title = `You clicked ${this.state.count} times`; } componentWillUnmount() { ChatAPI.unsubscribeFromFriendStatus( this.props.friend.id, this.handleStatusChange ); } handleStatusChange(status) { this.setState({ isOnline: status.isOnline }); } // ...
  • 46. function FriendStatusWithCounter(props) { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); const [isOnline, setIsOnline] = useState(null); useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); // ... }
  • 47. Hooks lets us organize logic into reusable isolated units
  • 50. What will happen to React classes?
  • 52. How will hooks affect the core concepts of React?
  • 53. ✅ Everything you already know won't change ✅ Hooks provide a more direct API 👉 props 👉 state 👉 context 👉 refs 👉 lifecycle
  • 54. 😄 No more constructor 😄 No more bindings 😄 No more this 😄 Less code 😄 Cleaner code 😓 Learning curve 😓 Bigger React API surface 😓 Not all covered (yet) 😓 There are some rules
  • 55. ☝ Only from React functions ☝ Only on top level
  • 56. Hooks rely on call order.
  • 57. function Form() { // 1. Use the name state variable const [name, setName] = useState('Mary'); // 2. Use an effect for persisting the form useEffect(function persistForm() { localStorage.setItem('formData', name); }); // 3. Use the surname state variable const [surname, setSurname] = useState('Poppins'); // 4. Use an effect for updating the title useEffect(function updateTitle() { document.title = name + ' ' + surname; }); // ... }
  • 58. // ------------ // First render // ------------ useState('Mary') // 1. Initialize name state variable with 'Mary' useEffect(persistForm) // 2. Add an effect for persisting the form useState('Poppins') // 3. Initialize surname state variable useEffect(updateTitle) // 4. Add an effect for updating the title // ------------- // Second render // ------------- useState('Mary') // 1. Read name state variable (argument ignored) useEffect(persistForm) // 2. Replace the effect for persisting the form useState('Poppins') // 3. Read surname state variable (argument ignored) useEffect(updateTitle) // 4. Replace the effect for updating the title // ...
  • 59. // 🔴 We're breaking the rule by using a Hook in a condition if (name !== '') { useEffect(function persistForm() { localStorage.setItem('formData', name); }); }
  • 60. useState('Mary') // 1. Read name state variable (argument ignored) // useEffect(persistForm) // 🔴 This Hook was skipped! useState('Poppins') // 🔴 2 (but was 3). Fail to read the surname state useEffect(updateTitle) // 🔴 3 (but was 4). Fail to replace the effect
  • 61. useEffect(function persistForm() { // 👍 We're not breaking the first rule anymore if (name !== '') { localStorage.setItem('formData', name); } });
  • 63. Start with useState when building new components
  • 64. Switch to useReducer on larger state shapes
  • 68. How to do I test React Hooks?
  • 71. @glnnrys 🔗 reactjs.org/hooks 🔗 nikgraf.github.io/react-hooks 🔗 github.com/rehooks/awesome-react-hooks 🔗 codesandbox.io/s/github/glennreyes/hooks-demo
  • 72. Glenn Reyes @glnnrys Thank you! 🔗 reactjs.org/hooks 🔗 nikgraf.github.io/react-hooks 🔗 github.com/rehooks/awesome-react-hooks 🔗 codesandbox.io/s/github/glennreyes/hooks-demo