SlideShare a Scribd company logo
Understanding React hooks | Walkingtree Technologies
What do we do?
● An I.T Software and Service provider company.
● We acts as an extended team for the customers across the globe like Capgemini, Tech Mahindra, Tibco, HP,
Infosys, Qualcomm, TCS to name a few and deliver end-to-end products and solutions to ensure “Great User
Experience”.
● Specialization in technology solutions from designing, development, quality assurance, maintenance and
support, consulting, training and skill augmentation services
● Technical Expertise in React, Angular, Blockchain, Microservices, Sencha ExtJS, Xamarin.
● Recognised as 50 Best Indian founded companies by The Silicon Review.
Presenter’s Introduction
Abhilasha Sinha
Technology Consultant
Abhilasha has worked in the technology industry for over 16 years.
Her core strength is designing & building complex enterprise web and
mobile application(s) using React, Angular.
Associated with WalkingTree for over 3 Years and playing role of
Technology Consultant
● React and its component structure
● What are Hooks?
● React Hooks and their capabilities
● Migrating Your Existing Apps to React Hooks
● Combine Existing React Hooks into New Custom Hooks
● Benefits of using React Hooks
● Best Practices
Agenda
React Components
React and its component structure
● The UI of React applications is made up of components.
● React provides the capability to define components in two ways:
○ Functional Components
function Welcome(props) {
return <h1>Hello, {props.name} !</h1>;
}
OR
const element = <Welcome name="WTT" />;
○ Class Components
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
React and its component structure(CONTD.)
● Before the arrival of React Hooks, the main difference between the Functional and Class components was
○ Class components have the Capability of handling local state at Component level
○ Class components have lifecycle methods associated with events of the component life which can be
implemented as needed to tap the event and add some functionality. For. e.g. componentDidMount(after
mounting), componentDidUpdate(after update), componentWillUnMount(before unmounting)
● Functional components were only for presentation purpose as they could not handle any state of their own and
had no special methods.
React Hooks
What are React Hooks?
“Hooks represent the vision of the future of React”
● React Hooks are functions that let us hook into the React state and lifecycle features for functional
components.
.
● Reusing Logic
○ Before hooks, reuse was possible using Higher order components and render props, i.e. passing
functions as props. This required restructuring your app, sometimes to include additional
components.
● Giant Components
○ Huge components with multiple lifecycle methods handling different pieces of logic
● Confusing Classes
○ Can we really do without the concept of classes??
■ Classes are hard for humans, but it's not just humans, classes are also hard for machines --
Sophie Alpert
■ Binding Issues, Performance Issues, Strict hierarchies
Why Hooks?(answers from the now-famous talk at React Conf 2018 as to what in React sucks)
React Hooks and their capabilities
Const[state,
dispatch]=useReducer(reducerFunction,
initialState);
● Single hook which handles state initialization as
well as actions on the state dispatched in the
form of events.
newRef = useRef(‘’);
● useRef is used to get a reference to the DOM
or any other element which can be referred
and manipulated directly
useRef
useEffect(()=>{
//Logic to handle
},secondParameter);
secondParameter will decide how many
times the logic is invoked
● This is an equivalent for class
lifecycle methods ( componentDidMount
componentDidUpdate,componentWillUnMount)
● Can be controlled using the second dependency
parameter
const [ users, setUsers]= useState([]);
● Define state structure by giving initial value
● Returns a reference to current state value
and a function(like setState) to set the new
value for state
useState
useEffect
useReducer
example
example
● If any of the value in the array changes, the callback will be
fired after every render.
● When it’s not present, the callback will always be fired after
every render.
● When it’s an empty list, the callback will only be fired once,
similar to componentDidMount.
React Hooks and their capabilities
const memoizedCallback = useCallback(
() => {
dosomeLogic(a, b);
},
[a, b],
);
● Takes an inline callback and an array of
dependencies and returns a memoized callback
which changes only if any of the dependencies
change.
● Used for optimization while passing the callback
as a prop to avoid unnecessary render.
const memoizedValue = useMemo(() =>
computeValue(a, b), [a, b]);
● Takes a function and an array of
dependencies and returns a memoized
value which will be recalculated when
one of the dependencies change.
● Used for performance optimization
const value = useContext(MyContext);
● To get the current value of a context
object
● Equivalent to a context Consumer
● Simpler and cleaner syntax
useContext
useMemo
useCallback
Rules for
React Hooks
Never call Hooks from
inside a loop, condition or
nested function
Hooks should sit at the
top-level of your component
Only call Hooks from React
functional components
Never call a Hook from a
regular function
Hooks can call other Hooks
● In order to implement hooks in your existing apps, you can follow the steps:
Convert Class components
to Functional
components(Remove this
keyword wherever used. No
more classes and no more this)!
The existing state can be
converted to single or
multiple pieces of state
depending on the usage.
Always remember to initialise
state.
You can make use of
useState to handle state
definition and initialization.
You can replace the lifecycle
methods(componentDidMoun
t, componentDidUpdate,
componentWillUnmount) logic
with the single useEffect
hook.
You can use useReducer
hook to handle different
actions on state at one place.
You can segregate all the
hook related logic into a
custom hook and use across
components.(We will see how
this can be done in next slide)
● React official does recommend to start using functional components as the preferred way to define
components due to advantages they provide.
Migrating Your Existing Apps to React Hooks
● React provides the capability of defining custom hooks which can be defined and used just like the
predefined react hooks.
● Custom hooks are functions used for accessing and manipulating state with use of standard React hooks.
● All the hook related logic using the standard hooks can be defined in a separate js file and named with a
use prefix to indicate that it is a custom hook.
● This can be imported like a standard hook in any component and used to get the entire state logic
available for reuse.
● It is not the same copy of state when the custom hook is reused and every component which uses it, gets
its own local copy of the state.
● It provides for capability of defining the logic once and using it as many number of times as needed.
Example - https://codesandbox.io/s/react-custom-hooks-demo-gtrr0
● This capability has enabled the React community to come up with many new hooks providing reusable
logic. This website provides a consolidated collection - https://nikgraf.github.io/react-hooks/
Combine Existing React Hooks into New Custom Hooks
The functional component code is cleaner and easier to
understand.1
Component State can also be split as related pieces put together.
3
Custom hooks can be created enabling to reuse the entire state
logic available which is not possible in class components.5
Hooks let you split state logic into smaller functions, based on which pieces
are related.
2
Hooks are fast. Some performance tests conducted on class vs functional
components performed on simple counter component showed the
functional component using hooks to be faster than class components by
3%. Also hooks may work better with future React optimizations (like
ahead of time compilation and components folding) .
4
Benefits of using React Hooks
Understanding React hooks | Walkingtree Technologies
● Write small and simple hooks.
● Don’t break related state into separate pieces such that update in one triggers an update of
the other causing unnecessary renders.
● Don’t create custom hooks just for the sake of it. Also while returning values in custom hooks
make sure you return an updated value only if it really changed to avoid unnecessary render.
● Make use of libraries like why-did-you-render library that tells you about avoidable
re-renders. To use it, mark your component as TestComponent.whyDidYouRender = true,
start using it, and look for messages in the console showing if it is being rerendered
unnecessarily.
● Keep the hooks logic organized and in the normal conventional lifecycle flow to make the
code easily understandable.
Best Practices
Questions and Answers

More Related Content

What's hot (20)

PPTX
React hooks
Sadhna Rana
 
PPTX
React hooks
Ramy ElBasyouni
 
PDF
Getting Started with NgRx (Redux) Angular
Gustavo Costa
 
PPTX
React js for beginners
Alessandro Valenti
 
PPTX
Its time to React.js
Ritesh Mehrotra
 
PPTX
React state
Ducat
 
PPTX
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
PDF
Important React Hooks
Knoldus Inc.
 
PDF
React js
Rajesh Kolla
 
PPTX
Reactjs
Neha Sharma
 
PDF
ReactJS presentation
Thanh Tuong
 
PPTX
React js programming concept
Tariqul islam
 
PDF
An introduction to React.js
Emanuele DelBono
 
PPTX
Intro to React
Justin Reock
 
ODP
Introduction to ReactJS
Knoldus Inc.
 
PDF
React Context API
NodeXperts
 
PPTX
React workshop
Imran Sayed
 
PDF
React js use contexts and useContext hook
Piyush Jamwal
 
PPTX
What is component in reactjs
manojbkalla
 
PPTX
React Class Components vs Functional Components: Which is Better?
Fibonalabs
 
React hooks
Sadhna Rana
 
React hooks
Ramy ElBasyouni
 
Getting Started with NgRx (Redux) Angular
Gustavo Costa
 
React js for beginners
Alessandro Valenti
 
Its time to React.js
Ritesh Mehrotra
 
React state
Ducat
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
Important React Hooks
Knoldus Inc.
 
React js
Rajesh Kolla
 
Reactjs
Neha Sharma
 
ReactJS presentation
Thanh Tuong
 
React js programming concept
Tariqul islam
 
An introduction to React.js
Emanuele DelBono
 
Intro to React
Justin Reock
 
Introduction to ReactJS
Knoldus Inc.
 
React Context API
NodeXperts
 
React workshop
Imran Sayed
 
React js use contexts and useContext hook
Piyush Jamwal
 
What is component in reactjs
manojbkalla
 
React Class Components vs Functional Components: Which is Better?
Fibonalabs
 

Similar to Understanding React hooks | Walkingtree Technologies (20)

PDF
100 React Interview questions 2024.pptx.pdf
codevincent624
 
PPTX
React-JS.pptx
AnmolPandita7
 
PDF
Importance of Hook in Recat Js.pdf
Nishaadequateinfosof
 
PDF
How to create components in ReactJS_.pdf
BOSC Tech Labs
 
PDF
Fundamental concepts of react js
StephieJohn
 
PPTX
This Is the ppt of How the react js work in the dealy life
AmanKoli6
 
PPTX
ReactJs Training in Hyderabad | ReactJS Training
eshwarvisualpath
 
PPTX
Green Custard Friday Talk 21: React Hooks
Green Custard
 
PPTX
Foster - Getting started with Angular
MukundSonaiya1
 
PPTX
React Hooks Best Practices in 2022.pptx
BOSC Tech Labs
 
PPTX
React JS: A Secret Preview
valuebound
 
PDF
How to build a react native app with the help of react native hooks
Katy Slemon
 
PPTX
Unit 2 Fundamentals of React -------.pptx
krishitajariwala72
 
PPTX
Presentation1
Kshitiz Rimal
 
PPTX
Presentation on "An Introduction to ReactJS"
Flipkart
 
PDF
unit 3_Adv WTAdvanced Web Tecg Design_HTML_CSS_JAVASCRIPT_AJAX_PPT.pdf
GauravDwivedi695361
 
PPTX
Session 03_04-Working with React Native.pptx
VHiu94
 
PPTX
Getting started with react &amp; redux
Girish Talekar
 
PDF
Getting started with react basics
Knoldus Inc.
 
PDF
React Interview Question PDF By ScholarHat
Scholarhat
 
100 React Interview questions 2024.pptx.pdf
codevincent624
 
React-JS.pptx
AnmolPandita7
 
Importance of Hook in Recat Js.pdf
Nishaadequateinfosof
 
How to create components in ReactJS_.pdf
BOSC Tech Labs
 
Fundamental concepts of react js
StephieJohn
 
This Is the ppt of How the react js work in the dealy life
AmanKoli6
 
ReactJs Training in Hyderabad | ReactJS Training
eshwarvisualpath
 
Green Custard Friday Talk 21: React Hooks
Green Custard
 
Foster - Getting started with Angular
MukundSonaiya1
 
React Hooks Best Practices in 2022.pptx
BOSC Tech Labs
 
React JS: A Secret Preview
valuebound
 
How to build a react native app with the help of react native hooks
Katy Slemon
 
Unit 2 Fundamentals of React -------.pptx
krishitajariwala72
 
Presentation1
Kshitiz Rimal
 
Presentation on "An Introduction to ReactJS"
Flipkart
 
unit 3_Adv WTAdvanced Web Tecg Design_HTML_CSS_JAVASCRIPT_AJAX_PPT.pdf
GauravDwivedi695361
 
Session 03_04-Working with React Native.pptx
VHiu94
 
Getting started with react &amp; redux
Girish Talekar
 
Getting started with react basics
Knoldus Inc.
 
React Interview Question PDF By ScholarHat
Scholarhat
 
Ad

Recently uploaded (20)

PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Ad

Understanding React hooks | Walkingtree Technologies

  • 2. What do we do? ● An I.T Software and Service provider company. ● We acts as an extended team for the customers across the globe like Capgemini, Tech Mahindra, Tibco, HP, Infosys, Qualcomm, TCS to name a few and deliver end-to-end products and solutions to ensure “Great User Experience”. ● Specialization in technology solutions from designing, development, quality assurance, maintenance and support, consulting, training and skill augmentation services ● Technical Expertise in React, Angular, Blockchain, Microservices, Sencha ExtJS, Xamarin. ● Recognised as 50 Best Indian founded companies by The Silicon Review.
  • 3. Presenter’s Introduction Abhilasha Sinha Technology Consultant Abhilasha has worked in the technology industry for over 16 years. Her core strength is designing & building complex enterprise web and mobile application(s) using React, Angular. Associated with WalkingTree for over 3 Years and playing role of Technology Consultant
  • 4. ● React and its component structure ● What are Hooks? ● React Hooks and their capabilities ● Migrating Your Existing Apps to React Hooks ● Combine Existing React Hooks into New Custom Hooks ● Benefits of using React Hooks ● Best Practices Agenda
  • 6. React and its component structure ● The UI of React applications is made up of components. ● React provides the capability to define components in two ways: ○ Functional Components function Welcome(props) { return <h1>Hello, {props.name} !</h1>; } OR const element = <Welcome name="WTT" />; ○ Class Components class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
  • 7. React and its component structure(CONTD.) ● Before the arrival of React Hooks, the main difference between the Functional and Class components was ○ Class components have the Capability of handling local state at Component level ○ Class components have lifecycle methods associated with events of the component life which can be implemented as needed to tap the event and add some functionality. For. e.g. componentDidMount(after mounting), componentDidUpdate(after update), componentWillUnMount(before unmounting) ● Functional components were only for presentation purpose as they could not handle any state of their own and had no special methods.
  • 9. What are React Hooks? “Hooks represent the vision of the future of React” ● React Hooks are functions that let us hook into the React state and lifecycle features for functional components. .
  • 10. ● Reusing Logic ○ Before hooks, reuse was possible using Higher order components and render props, i.e. passing functions as props. This required restructuring your app, sometimes to include additional components. ● Giant Components ○ Huge components with multiple lifecycle methods handling different pieces of logic ● Confusing Classes ○ Can we really do without the concept of classes?? ■ Classes are hard for humans, but it's not just humans, classes are also hard for machines -- Sophie Alpert ■ Binding Issues, Performance Issues, Strict hierarchies Why Hooks?(answers from the now-famous talk at React Conf 2018 as to what in React sucks)
  • 11. React Hooks and their capabilities Const[state, dispatch]=useReducer(reducerFunction, initialState); ● Single hook which handles state initialization as well as actions on the state dispatched in the form of events. newRef = useRef(‘’); ● useRef is used to get a reference to the DOM or any other element which can be referred and manipulated directly useRef useEffect(()=>{ //Logic to handle },secondParameter); secondParameter will decide how many times the logic is invoked ● This is an equivalent for class lifecycle methods ( componentDidMount componentDidUpdate,componentWillUnMount) ● Can be controlled using the second dependency parameter const [ users, setUsers]= useState([]); ● Define state structure by giving initial value ● Returns a reference to current state value and a function(like setState) to set the new value for state useState useEffect useReducer example example ● If any of the value in the array changes, the callback will be fired after every render. ● When it’s not present, the callback will always be fired after every render. ● When it’s an empty list, the callback will only be fired once, similar to componentDidMount.
  • 12. React Hooks and their capabilities const memoizedCallback = useCallback( () => { dosomeLogic(a, b); }, [a, b], ); ● Takes an inline callback and an array of dependencies and returns a memoized callback which changes only if any of the dependencies change. ● Used for optimization while passing the callback as a prop to avoid unnecessary render. const memoizedValue = useMemo(() => computeValue(a, b), [a, b]); ● Takes a function and an array of dependencies and returns a memoized value which will be recalculated when one of the dependencies change. ● Used for performance optimization const value = useContext(MyContext); ● To get the current value of a context object ● Equivalent to a context Consumer ● Simpler and cleaner syntax useContext useMemo useCallback
  • 13. Rules for React Hooks Never call Hooks from inside a loop, condition or nested function Hooks should sit at the top-level of your component Only call Hooks from React functional components Never call a Hook from a regular function Hooks can call other Hooks
  • 14. ● In order to implement hooks in your existing apps, you can follow the steps: Convert Class components to Functional components(Remove this keyword wherever used. No more classes and no more this)! The existing state can be converted to single or multiple pieces of state depending on the usage. Always remember to initialise state. You can make use of useState to handle state definition and initialization. You can replace the lifecycle methods(componentDidMoun t, componentDidUpdate, componentWillUnmount) logic with the single useEffect hook. You can use useReducer hook to handle different actions on state at one place. You can segregate all the hook related logic into a custom hook and use across components.(We will see how this can be done in next slide) ● React official does recommend to start using functional components as the preferred way to define components due to advantages they provide. Migrating Your Existing Apps to React Hooks
  • 15. ● React provides the capability of defining custom hooks which can be defined and used just like the predefined react hooks. ● Custom hooks are functions used for accessing and manipulating state with use of standard React hooks. ● All the hook related logic using the standard hooks can be defined in a separate js file and named with a use prefix to indicate that it is a custom hook. ● This can be imported like a standard hook in any component and used to get the entire state logic available for reuse. ● It is not the same copy of state when the custom hook is reused and every component which uses it, gets its own local copy of the state. ● It provides for capability of defining the logic once and using it as many number of times as needed. Example - https://codesandbox.io/s/react-custom-hooks-demo-gtrr0 ● This capability has enabled the React community to come up with many new hooks providing reusable logic. This website provides a consolidated collection - https://nikgraf.github.io/react-hooks/ Combine Existing React Hooks into New Custom Hooks
  • 16. The functional component code is cleaner and easier to understand.1 Component State can also be split as related pieces put together. 3 Custom hooks can be created enabling to reuse the entire state logic available which is not possible in class components.5 Hooks let you split state logic into smaller functions, based on which pieces are related. 2 Hooks are fast. Some performance tests conducted on class vs functional components performed on simple counter component showed the functional component using hooks to be faster than class components by 3%. Also hooks may work better with future React optimizations (like ahead of time compilation and components folding) . 4 Benefits of using React Hooks
  • 18. ● Write small and simple hooks. ● Don’t break related state into separate pieces such that update in one triggers an update of the other causing unnecessary renders. ● Don’t create custom hooks just for the sake of it. Also while returning values in custom hooks make sure you return an updated value only if it really changed to avoid unnecessary render. ● Make use of libraries like why-did-you-render library that tells you about avoidable re-renders. To use it, mark your component as TestComponent.whyDidYouRender = true, start using it, and look for messages in the console showing if it is being rerendered unnecessarily. ● Keep the hooks logic organized and in the normal conventional lifecycle flow to make the code easily understandable. Best Practices