SlideShare a Scribd company logo
Enhancing functional components
Fullstack as a service
React Hooks
React component Types
Stateless
● Pure function with no side-effects
● No internal state
● No lifecycle hooks
● Simple
● Easy to reuse
● Easy to test
Stateful
● Class components
● Retain internal state
● Enables lifecycle interaction
● Complex
● Not easy to test internal logic
What are hooks
Functions that enhance Functional Components with state maintaining and
side-effects capabilities
Why do we need them?
● Class components become complex and difficult to maintain and test
● Class components lifecycle functions group different logic and cause
confusion.
● More reusable code
● Reduce complexity of HoC layers
The setState hook
const [stateVal, updateValFn] = React.useState(initialVal)
Export class Counter extends React.Component {
state = {
counter: 0,
};
setCounter = (val) => {
this.setState(val);
}
render() {
const { counter } = this.state;
return (
<div className="App">
<div>{counter}</div>
<div>
<button onClick={() => this.setCounter(counter + 1)}>+1</button>
<button onClick={() => this.setCounter(counter - 1)}>-1</button>
</div>
</div>
);
}
}
import React from 'react';
export function Counter() {
const [counter, setCounter] = React.useState(0);
return (
<div className="App">
<div>{counter}</div>
<div>
<button onClick={() => setCounter(counter + 1)}>+1</button>
<button onClick={() => setCounter(counter - 1)}>-1</button>
</div>
</div>
);
}
Practice Time
Create Functional Component with useState
The useEffect hook
Used to add side effect capabilities to the functional component. This is a
combination of componentDidMount, componentDidUpdate, and
componentWillUnmount
React.useEffect(sideEffecFn, [dependencies]): cleanupFn
● sideEfectFn: A function that can perform a side effect, e.g. async call to
fetch data
● dependencies (Array): A list of values that if changed will trigger the
sideEffectFn and cause a re-render
● cleanupFn: the (optional) returned value of the side effect - triggered
before each re-render - used for cleaning up, e.g. unregistering from
events
React.useEffect(sideEffecFn, [dependencies]): cleanupFn
class Example extends React.Component {
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>
);
}
}
import React, { useState, useEffect } from 'react';
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>
);
}
The dependencies optional parameter
Every time the component renders the effect is ‘useEfect’ is triggered.
It compares the values in this array to the values of the previous execution.
If the values do not change then the sideEffectFn will not re-execute.
● No array given (undefined) - will execute on every render
(componentDidMount + componentDidUpdate)
● An empty array given - will execute once (componentDidMount)
● Array with values - will execute only if one of the values has changed
Practice Time
Create country auto-complete using useEffect
https://restcountries.eu/rest/v2/name/:query
Build your own hooks
Custom hooks are reusable functions that encapsulate useState and
useEffect methods
import React, { useState, useEffect } from 'react';
function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
};
});
return isOnline;
}
function FriendStatus(props) {
const isOnline = useFriendStatus(props.friend.id);
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
function FriendListItem(props) {
const isOnline = useFriendStatus(props.friend.id);
return (
<li style={{ color: isOnline ? 'green' : 'black' }}>
{props.friend.name}
</li>
);
}}
Practice:
Create a ‘useCountryName’ hook.
It will accept a country ISO code (e.g. ISR) and return the country name.
http://restcountries.eu/rest/v2/alpha/ISR
More Hooks
● useContext
● useReducer
● useCallback
● useMemo
● useRef
The useContext hook
Gives access to the component’s context if a context provider was set higher
in the hierarchy
const value = useContext(MyContext);
Practice
Extract the api client (has a “fetch” function) and pass it in as Context
import React from "react";
export const apiClient = {
getData: (query: string) =>
fetch(`https://restcountries.eu/rest/v2/name/${query}`)
.then(res => res.json())
.then(countries => countries.map((c: any) => c.name))
};
export const ApiContext = React.createContext(apiClient);
import React from "react";
import { Search } from "./components/Serach";
import { ApiContext, apiClient } from "./api/ApiClient";
const App: React.FC = () => {
return (
<ApiContext.Provider value={apiClient}>
<div className="App">
<Search />
</div>
</ApiContext.Provider>
);
};
export default App;
const apiClient = useContext(ApiContext);
useEffect(() => {
if (query) {
apiClient.getData(query).then(names => setCountries(names));
}
}, [query]);
The useReducer hook
Similar to useState
const [state, dispatch] = useReducer(reducer, initialArg, init);
When do we use it?
Instead of passing down callbacks to update the state in a large component
tree - you can pass the dispatch function in the context
const TodosDispatch = React.createContext(null);
function TodosApp() {
// Note: `dispatch` won't change between re-renders
const [todos, dispatch] = useReducer(todosReducer);
return (
<TodosDispatch.Provider value={dispatch}>
<DeepTree todos={todos} />
</TodosDispatch.Provider>
);
}
function DeepChild(props) {
// If we want to perform an action, we can get dispatch
from context.
const dispatch = useContext(TodosDispatch);
function handleClick() {
dispatch({ type: 'add', text: 'hello' });
}
return (
<button onClick={handleClick}>Add todo</button>
);
}
The useCallback hook
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);
When to use it?
When passing a function to children - avoid re-rendering due to new function
creation.
Render checks use ‘===’ comparison of params
The useMemo hook
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Practice:
1. Extract the search button to a seperate component - “SearchButton”
2. Prevent the SearchButton component from re-rendering on every text
change.
The useRef hook
const refContainer = useRef(initialValue);
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}

More Related Content

What's hot

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 HooksSoluto
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_jsMicroPyramid .
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksMaulik Shah
 
React Context API
React Context APIReact Context API
React Context APINodeXperts
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux jsCitrix
 
Important React Hooks
Important React HooksImportant React Hooks
Important React HooksKnoldus Inc.
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjsmanojbkalla
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 

What's hot (20)

React JS
React JSReact JS
React JS
 
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
 
React and redux
React and reduxReact and redux
React and redux
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
ReactJS
ReactJSReactJS
ReactJS
 
React Context API
React Context APIReact Context API
React Context API
 
React js
React jsReact js
React js
 
Getting started with Redux js
Getting started with Redux jsGetting started with Redux js
Getting started with Redux js
 
Important React Hooks
Important React HooksImportant React Hooks
Important React Hooks
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
React js
React jsReact js
React js
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
 
ReactJs
ReactJsReactJs
ReactJs
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 

Similar to React hooks

Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react applicationGreg Bergé
 
Battle of React State Managers in frontend applications
Battle of React State Managers in frontend applicationsBattle of React State Managers in frontend applications
Battle of React State Managers in frontend applicationsEvangelia Mitsopoulou
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projectsIgnacio Martín
 
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JS Fest 2019. Glenn Reyes. With great power comes great React hooks!
JS Fest 2019. Glenn Reyes. With great power comes great React hooks!JSFestUA
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render PropsNitish Phanse
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법Jeado Ko
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab AcademyDreamLab
 
React JS Hooks Sheet .pdf
React JS Hooks Sheet .pdfReact JS Hooks Sheet .pdf
React JS Hooks Sheet .pdfnishant078cs23
 
React Back to the Future
React Back to the FutureReact Back to the Future
React Back to the Future500Tech
 
Your IDE Deserves Better
Your IDE Deserves BetterYour IDE Deserves Better
Your IDE Deserves BetterBoris Litvinsky
 
React 16: new features and beyond
React 16: new features and beyondReact 16: new features and beyond
React 16: new features and beyondArtjoker
 
How do we use hooks
How do we use hooksHow do we use hooks
How do we use hooksJim Liu
 
react-hooks.pdf
react-hooks.pdfreact-hooks.pdf
react-hooks.pdfchengbo xu
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs[T]echdencias
 

Similar to React hooks (20)

Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react application
 
Battle of React State Managers in frontend applications
Battle of React State Managers in frontend applicationsBattle of React State Managers in frontend applications
Battle of React State Managers in frontend applications
 
React redux
React reduxReact redux
React redux
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
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!
 
Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab Academy
 
React lecture
React lectureReact lecture
React lecture
 
React JS Hooks Sheet .pdf
React JS Hooks Sheet .pdfReact JS Hooks Sheet .pdf
React JS Hooks Sheet .pdf
 
React Back to the Future
React Back to the FutureReact Back to the Future
React Back to the Future
 
Your IDE Deserves Better
Your IDE Deserves BetterYour IDE Deserves Better
Your IDE Deserves Better
 
React 16: new features and beyond
React 16: new features and beyondReact 16: new features and beyond
React 16: new features and beyond
 
How do we use hooks
How do we use hooksHow do we use hooks
How do we use hooks
 
react-hooks.pdf
react-hooks.pdfreact-hooks.pdf
react-hooks.pdf
 
React 101
React 101React 101
React 101
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
 
React outbox
React outboxReact outbox
React outbox
 

More from Assaf Gannon

Serverless in-action
Serverless in-actionServerless in-action
Serverless in-actionAssaf Gannon
 
Serverless meets GraphQL
Serverless meets GraphQLServerless meets GraphQL
Serverless meets GraphQLAssaf Gannon
 
Serverless and GraphQL
Serverless and GraphQLServerless and GraphQL
Serverless and GraphQLAssaf Gannon
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programmingAssaf Gannon
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programmingAssaf Gannon
 
Reactive Architecture
Reactive ArchitectureReactive Architecture
Reactive ArchitectureAssaf Gannon
 
Software Architecture Patterns
Software Architecture PatternsSoftware Architecture Patterns
Software Architecture PatternsAssaf Gannon
 
Fullstack workshop
Fullstack workshopFullstack workshop
Fullstack workshopAssaf Gannon
 
TabTale Architecture Overview
TabTale Architecture OverviewTabTale Architecture Overview
TabTale Architecture OverviewAssaf Gannon
 
From server generated pages to client app in a micro-services world
From server generated pages to client app in a micro-services worldFrom server generated pages to client app in a micro-services world
From server generated pages to client app in a micro-services worldAssaf Gannon
 

More from Assaf Gannon (11)

Serverless in-action
Serverless in-actionServerless in-action
Serverless in-action
 
Serverless meets GraphQL
Serverless meets GraphQLServerless meets GraphQL
Serverless meets GraphQL
 
Serverless and GraphQL
Serverless and GraphQLServerless and GraphQL
Serverless and GraphQL
 
Micro frontends
Micro frontendsMicro frontends
Micro frontends
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Reactive Architecture
Reactive ArchitectureReactive Architecture
Reactive Architecture
 
Software Architecture Patterns
Software Architecture PatternsSoftware Architecture Patterns
Software Architecture Patterns
 
Fullstack workshop
Fullstack workshopFullstack workshop
Fullstack workshop
 
TabTale Architecture Overview
TabTale Architecture OverviewTabTale Architecture Overview
TabTale Architecture Overview
 
From server generated pages to client app in a micro-services world
From server generated pages to client app in a micro-services worldFrom server generated pages to client app in a micro-services world
From server generated pages to client app in a micro-services world
 

Recently uploaded

AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAlluxio, Inc.
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownloadvrstrong314
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfkalichargn70th171
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfmbmh111980
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Krakówbim.edu.pl
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockSkilrock Technologies
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...Alluxio, Inc.
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAlluxio, Inc.
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion Clinic
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationWave PLM
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEJelle | Nordend
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAlluxio, Inc.
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1KnowledgeSeed
 

Recently uploaded (20)

AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by Skilrock
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 

React hooks

  • 1. Enhancing functional components Fullstack as a service React Hooks
  • 2. React component Types Stateless ● Pure function with no side-effects ● No internal state ● No lifecycle hooks ● Simple ● Easy to reuse ● Easy to test Stateful ● Class components ● Retain internal state ● Enables lifecycle interaction ● Complex ● Not easy to test internal logic
  • 3. What are hooks Functions that enhance Functional Components with state maintaining and side-effects capabilities
  • 4. Why do we need them? ● Class components become complex and difficult to maintain and test ● Class components lifecycle functions group different logic and cause confusion. ● More reusable code ● Reduce complexity of HoC layers
  • 5. The setState hook const [stateVal, updateValFn] = React.useState(initialVal)
  • 6. Export class Counter extends React.Component { state = { counter: 0, }; setCounter = (val) => { this.setState(val); } render() { const { counter } = this.state; return ( <div className="App"> <div>{counter}</div> <div> <button onClick={() => this.setCounter(counter + 1)}>+1</button> <button onClick={() => this.setCounter(counter - 1)}>-1</button> </div> </div> ); } }
  • 7. import React from 'react'; export function Counter() { const [counter, setCounter] = React.useState(0); return ( <div className="App"> <div>{counter}</div> <div> <button onClick={() => setCounter(counter + 1)}>+1</button> <button onClick={() => setCounter(counter - 1)}>-1</button> </div> </div> ); }
  • 10. The useEffect hook Used to add side effect capabilities to the functional component. This is a combination of componentDidMount, componentDidUpdate, and componentWillUnmount React.useEffect(sideEffecFn, [dependencies]): cleanupFn
  • 11. ● sideEfectFn: A function that can perform a side effect, e.g. async call to fetch data ● dependencies (Array): A list of values that if changed will trigger the sideEffectFn and cause a re-render ● cleanupFn: the (optional) returned value of the side effect - triggered before each re-render - used for cleaning up, e.g. unregistering from events React.useEffect(sideEffecFn, [dependencies]): cleanupFn
  • 12. class Example extends React.Component { 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> ); } }
  • 13. import React, { useState, useEffect } from 'react'; 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> ); }
  • 14. The dependencies optional parameter Every time the component renders the effect is ‘useEfect’ is triggered. It compares the values in this array to the values of the previous execution. If the values do not change then the sideEffectFn will not re-execute. ● No array given (undefined) - will execute on every render (componentDidMount + componentDidUpdate) ● An empty array given - will execute once (componentDidMount) ● Array with values - will execute only if one of the values has changed
  • 16. Create country auto-complete using useEffect https://restcountries.eu/rest/v2/name/:query
  • 17. Build your own hooks Custom hooks are reusable functions that encapsulate useState and useEffect methods
  • 18. import React, { useState, useEffect } from 'react'; function useFriendStatus(friendID) { const [isOnline, setIsOnline] = useState(null); useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange); }; }); return isOnline; }
  • 19. function FriendStatus(props) { const isOnline = useFriendStatus(props.friend.id); if (isOnline === null) { return 'Loading...'; } return isOnline ? 'Online' : 'Offline'; } function FriendListItem(props) { const isOnline = useFriendStatus(props.friend.id); return ( <li style={{ color: isOnline ? 'green' : 'black' }}> {props.friend.name} </li> ); }}
  • 20. Practice: Create a ‘useCountryName’ hook. It will accept a country ISO code (e.g. ISR) and return the country name. http://restcountries.eu/rest/v2/alpha/ISR
  • 21. More Hooks ● useContext ● useReducer ● useCallback ● useMemo ● useRef
  • 22. The useContext hook Gives access to the component’s context if a context provider was set higher in the hierarchy const value = useContext(MyContext);
  • 23. Practice Extract the api client (has a “fetch” function) and pass it in as Context
  • 24. import React from "react"; export const apiClient = { getData: (query: string) => fetch(`https://restcountries.eu/rest/v2/name/${query}`) .then(res => res.json()) .then(countries => countries.map((c: any) => c.name)) }; export const ApiContext = React.createContext(apiClient);
  • 25. import React from "react"; import { Search } from "./components/Serach"; import { ApiContext, apiClient } from "./api/ApiClient"; const App: React.FC = () => { return ( <ApiContext.Provider value={apiClient}> <div className="App"> <Search /> </div> </ApiContext.Provider> ); }; export default App;
  • 26. const apiClient = useContext(ApiContext); useEffect(() => { if (query) { apiClient.getData(query).then(names => setCountries(names)); } }, [query]);
  • 27. The useReducer hook Similar to useState const [state, dispatch] = useReducer(reducer, initialArg, init);
  • 28. When do we use it? Instead of passing down callbacks to update the state in a large component tree - you can pass the dispatch function in the context
  • 29. const TodosDispatch = React.createContext(null); function TodosApp() { // Note: `dispatch` won't change between re-renders const [todos, dispatch] = useReducer(todosReducer); return ( <TodosDispatch.Provider value={dispatch}> <DeepTree todos={todos} /> </TodosDispatch.Provider> ); } function DeepChild(props) { // If we want to perform an action, we can get dispatch from context. const dispatch = useContext(TodosDispatch); function handleClick() { dispatch({ type: 'add', text: 'hello' }); } return ( <button onClick={handleClick}>Add todo</button> ); }
  • 30. The useCallback hook const memoizedCallback = useCallback( () => { doSomething(a, b); }, [a, b], );
  • 31. When to use it? When passing a function to children - avoid re-rendering due to new function creation. Render checks use ‘===’ comparison of params
  • 32. The useMemo hook const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  • 33. Practice: 1. Extract the search button to a seperate component - “SearchButton” 2. Prevent the SearchButton component from re-rendering on every text change.
  • 34. The useRef hook const refContainer = useRef(initialValue);
  • 35. function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` points to the mounted text input element inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }

Editor's Notes

  1. https://github.com/getify/TNG-Hooks/blob/master/src/tng-hooks.src.js