SlideShare a Scribd company logo
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
● 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)

React Hooks
React HooksReact Hooks
React Hooks
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
React with Redux
React with ReduxReact with Redux
React with Redux
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
ReactJs
ReactJsReactJs
ReactJs
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
reactJS
reactJSreactJS
reactJS
 
React hooks
React hooksReact hooks
React hooks
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
React js
React jsReact js
React js
 
React Class Components vs Functional Components: Which is Better?
React Class Components vs Functional Components: Which is Better?React Class Components vs Functional Components: Which is Better?
React Class Components vs Functional Components: Which is Better?
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Reactjs
Reactjs Reactjs
Reactjs
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to 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
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 

Similar to Understanding React hooks | Walkingtree Technologies

React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
Importance of Hook in Recat Js.pdf
Importance of Hook in Recat Js.pdfImportance of Hook in Recat Js.pdf
Importance of Hook in Recat Js.pdfNishaadequateinfosof
 
How to create components in ReactJS_.pdf
How to create components in ReactJS_.pdfHow to create components in ReactJS_.pdf
How to create components in ReactJS_.pdfBOSC Tech Labs
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
ReactJs Training in Hyderabad | ReactJS Training
ReactJs Training in Hyderabad  | ReactJS TrainingReactJs Training in Hyderabad  | ReactJS Training
ReactJs Training in Hyderabad | ReactJS Trainingeshwarvisualpath
 
Green Custard Friday Talk 21: React Hooks
Green Custard Friday Talk 21: React HooksGreen Custard Friday Talk 21: React Hooks
Green Custard Friday Talk 21: React HooksGreen Custard
 
Foster - Getting started with Angular
Foster - Getting started with AngularFoster - Getting started with Angular
Foster - Getting started with AngularMukundSonaiya1
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxBOSC Tech Labs
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksKaty Slemon
 
Unit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptxUnit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptxkrishitajariwala72
 
Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Flipkart
 
Getting started with react &amp; redux
Getting started with react &amp; reduxGetting started with react &amp; redux
Getting started with react &amp; reduxGirish Talekar
 
Getting started with react basics
Getting started with react basicsGetting started with react basics
Getting started with react basicsKnoldus Inc.
 
React state management and side-effects – A Review of Hooks
React state management and side-effects – A Review of HooksReact state management and side-effects – A Review of Hooks
React state management and side-effects – A Review of HooksIRJET Journal
 
Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Concetto Labs
 
React JS Interview Question & Answer
React JS Interview Question & AnswerReact JS Interview Question & Answer
React JS Interview Question & AnswerMildain Solutions
 

Similar to Understanding React hooks | Walkingtree Technologies (20)

React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
Importance of Hook in Recat Js.pdf
Importance of Hook in Recat Js.pdfImportance of Hook in Recat Js.pdf
Importance of Hook in Recat Js.pdf
 
How to create components in ReactJS_.pdf
How to create components in ReactJS_.pdfHow to create components in ReactJS_.pdf
How to create components in ReactJS_.pdf
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
ReactJs Training in Hyderabad | ReactJS Training
ReactJs Training in Hyderabad  | ReactJS TrainingReactJs Training in Hyderabad  | ReactJS Training
ReactJs Training in Hyderabad | ReactJS Training
 
Green Custard Friday Talk 21: React Hooks
Green Custard Friday Talk 21: React HooksGreen Custard Friday Talk 21: React Hooks
Green Custard Friday Talk 21: React Hooks
 
Foster - Getting started with Angular
Foster - Getting started with AngularFoster - Getting started with Angular
Foster - Getting started with Angular
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooks
 
Unit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptxUnit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptx
 
Presentation1
Presentation1Presentation1
Presentation1
 
Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"Presentation on "An Introduction to ReactJS"
Presentation on "An Introduction to ReactJS"
 
Getting started with react &amp; redux
Getting started with react &amp; reduxGetting started with react &amp; redux
Getting started with react &amp; redux
 
Getting started with react basics
Getting started with react basicsGetting started with react basics
Getting started with react basics
 
React state management and side-effects – A Review of Hooks
React state management and side-effects – A Review of HooksReact state management and side-effects – A Review of Hooks
React state management and side-effects – A Review of Hooks
 
Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...
 
React JS Interview Question & Answer
React JS Interview Question & AnswerReact JS Interview Question & Answer
React JS Interview Question & Answer
 
Redux in Angular 2+
Redux in Angular 2+Redux in Angular 2+
Redux in Angular 2+
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024Stephanie Beckett
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfChristopherTHyatt
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀DianaGray10
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...Product School
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...CzechDreamin
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekCzechDreamin
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 

Understanding React hooks | Walkingtree Technologies

  • 1.
  • 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
  • 17.
  • 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