SlideShare uma empresa Scribd logo
1 de 21
React Hooks
Erez Cohen
UI Architect at Perfecto (Perforce)
@erezcohentlv
Background
☞ Introduced in React version 16.8.
☞ Hooks enable adding state and side effects to Functional
Components.
☞ Essentially replace the need for Class components.
In the eyes of the React Team:
☞ What a true component should be: "A function with state".
☞ The mindset: Call a function for rendering.
Background
Classes Components are not “real classes”:
😐 We shouldn't inherit a class component.
😐 We cannot do dynamic binding (Polymorphism).
😐 We do not use the “new” keyword.
😐 We do not move around instances like we do with objects.
😐 Members go into ”State”?!
😐 What are props? (params to a function? a constructor?)
From an interview with Dan Abramov
Motivation
😺 Functionality Reuse:
- Extract repeating code to a custom hook (including state and side effects).
- Simpler then HOC (Higher Order Components) and "Render Props".
😺 Smaller code, co-located:
- E.g. useEffect() may replace code that was previously spread over several
lifecycle methods.
😺 Functional components are less verbose.
Let’s look at
⚡️ useState
⚡️ useReducer
⚡️ useEffect
⚡️ useCallback
⚡️ useMemo
⚡️ useRef
useState
Purpose: Use State (Duh).
Demo..
useState
Gotchas / Tips :
✍ Different from setState() of a class component: Does not merge!
✍ If we pass to it a func -> it will run only on the first time
❌ useState(calc(props)) // calc() will run every time
✅ useState(() => calc(props))
✍ Prefer using the functional way
(you’ll be less likely to encounter “Stale State” ).
useReducer
Purpose: Handle complex state.
useReducer
Tips:
⛰ Use immer to simplify.
⛰ Define the reducer outside of the component (enforce purity).
useEffect
Purpose: Handle side effects (mostly).
How depArr affects behavior:
Nothing → Run after each render / Cleanup before every next render
[] → Run only after mount / Cleanup before unmount
[deps...] → Run only after dependencies change / Cleanup before next render
Demo..
Or (named):
useEffect:
Gotchas / Tips :
✍ beware of one-liners – They might return a value:
❌
✍ Make sure you define a func for cleanup (instead of calling it):
❌
⚠️ Do not automatically ignore the ”exhaustive-deps” eslint rule as
it may indicate a bug in your code!
useEffect:
Gotchas / Tips:
✍ useEffect should only have “Stable References” as dependencies:
A stable ref is a reference which is constant. Examples:
✅ Consts we define outside the component (props too).
✅ The func returned from useState / useCallback().
✅ Variables we define with useRef().
❌ A const defined in a component → it is redefined on each run.
useLayoutEffect:
In some (rare) cases you'll want to do something synchronously
after a render. E.g., read / right to the DOM.
Then use useLayoutEffect() instead of useLayoutEffect().
useCallback
Purpose: Create a memoized function.
Useful for passing a funcion as dependency to:
♤ useEffect // otherwise we'll see the 'exhaustive-deps' lint error.
♤ a child component // avoid re-rendring the child on every parent render.
Demo..
useMemo
Purpose: Create a memoized value.
♤ Use as a performance enhancement:
In this case the app should work logically the same without it.
https://medium.com/javascript-in-plain-english/react-usememo-and-when-you-should-use-it-e69a106bbb02
♤ Can be used to replace useState + useEffect when useEffect does pure
calculations (i.e. no side effects).
https://stackoverflow.com/questions/56028913/usememo-vs-useeffect-usestate
useRef
Purpose: Creates a ”Stable Ref” / ref to the DOM.
♤ Returns an object with the attribute 'current’.
♤ Mutable.
♤ Mutations do not cause a re-render.
Demo..
useRef
Usages examples:
♤ Refer to a DOM element (like createRef() in classes):
=> Detect clicks outside the element, find its size etc.
♤ Store a mutable value across the lifespan of the component
(like placing a value on “this” in a class).
=> Access a var from different funcs, keep previous state etc.
⚠️ Modify refs in event handlers and effects, not the
“render” (=the body of the component).
Hooks Rules!
📜 Do not place hooks behind conditions!
Make sure all are called every time the component “runs”.
Best practice: Place at the top of the component.
📜 Call hooks only from functional components or custom hooks!
* Enforced using the eslint-plugin-react-hooks rules.
Custom Hooks
🚀 Enable logic reusability between (and within) components.
🚀 Added bonus: Hooks created by the community:
→ Gists.
→ Npm packages.
* Same hooks rules apply.
* The name should start with “use” (otherwise we lose the linter’s help).
Demo..
Links
📃 The official Docs: https://reactjs.org/docs/hooks-intro.html
📃 Useful hooks (for copy+paste): https://github.com/gragland/usehooks
📃 Useful hooks (as npm packages): https://github.com/gragland/usehooks
📃 Huge collection of hooks related links:
https://github.com/rehooks/awesome-react-hooks
Fin
(for now)

Mais conteúdo relacionado

Mais procurados

Important React Hooks
Important React HooksImportant React Hooks
Important React HooksKnoldus Inc.
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hookPiyush Jamwal
 
React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.ManojSatishKumar
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsANKUSH CHAVAN
 
React state
React  stateReact  state
React stateDucat
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react formYao Nien Chung
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJSKnoldus Inc.
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...Katy Slemon
 

Mais procurados (20)

Important React Hooks
Important React HooksImportant React Hooks
Important React Hooks
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 
React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.
 
ReactJS
ReactJSReactJS
ReactJS
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
React js
React jsReact js
React js
 
React state
React  stateReact  state
React state
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
React workshop
React workshopReact workshop
React workshop
 
React
React React
React
 
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
React render props
React render propsReact render props
React render props
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
Introduction to ReactJS
Introduction to ReactJSIntroduction to ReactJS
Introduction to ReactJS
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...How to implement internationalization (i18n) in angular application(multiple ...
How to implement internationalization (i18n) in angular application(multiple ...
 

Semelhante a React Hooks

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
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
Pluginkla2019 - React Presentation
Pluginkla2019 - React PresentationPluginkla2019 - React Presentation
Pluginkla2019 - React PresentationAngela Lehru
 
Everything You Need To Know About AngularJS
Everything You Need To Know About AngularJSEverything You Need To Know About AngularJS
Everything You Need To Know About AngularJSSina Mirhejazi
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfStephieJohn
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)Chiew Carol
 
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...Edureka!
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]GDSC UofT Mississauga
 
Unit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptxUnit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptxkrishitajariwala72
 
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
 
What are the components in React?
What are the components in React?What are the components in React?
What are the components in React?BOSC Tech Labs
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming PrinciplesAndrii Lundiak
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular IntermediateLinkMe Srl
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 
React for Dummies
React for DummiesReact for Dummies
React for DummiesMitch Chen
 
Content-Driven Apps with React
Content-Driven Apps with ReactContent-Driven Apps with React
Content-Driven Apps with ReactNetcetera
 

Semelhante a React Hooks (20)

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
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
Pluginkla2019 - React Presentation
Pluginkla2019 - React PresentationPluginkla2019 - React Presentation
Pluginkla2019 - React Presentation
 
Everything You Need To Know About AngularJS
Everything You Need To Know About AngularJSEverything You Need To Know About AngularJS
Everything You Need To Know About AngularJS
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Unit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptxUnit 2 Fundamentals of React -------.pptx
Unit 2 Fundamentals of React -------.pptx
 
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
 
Simple React Todo List
Simple React Todo ListSimple React Todo List
Simple React Todo List
 
Angular js-crash-course
Angular js-crash-courseAngular js-crash-course
Angular js-crash-course
 
What are the components in React?
What are the components in React?What are the components in React?
What are the components in React?
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
Content-Driven Apps with React
Content-Driven Apps with ReactContent-Driven Apps with React
Content-Driven Apps with React
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 

Último

%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile EnvironmentVictorSzoltysek
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 

Último (20)

%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

React Hooks

  • 1. React Hooks Erez Cohen UI Architect at Perfecto (Perforce) @erezcohentlv
  • 2. Background ☞ Introduced in React version 16.8. ☞ Hooks enable adding state and side effects to Functional Components. ☞ Essentially replace the need for Class components. In the eyes of the React Team: ☞ What a true component should be: "A function with state". ☞ The mindset: Call a function for rendering.
  • 3. Background Classes Components are not “real classes”: 😐 We shouldn't inherit a class component. 😐 We cannot do dynamic binding (Polymorphism). 😐 We do not use the “new” keyword. 😐 We do not move around instances like we do with objects. 😐 Members go into ”State”?! 😐 What are props? (params to a function? a constructor?) From an interview with Dan Abramov
  • 4. Motivation 😺 Functionality Reuse: - Extract repeating code to a custom hook (including state and side effects). - Simpler then HOC (Higher Order Components) and "Render Props". 😺 Smaller code, co-located: - E.g. useEffect() may replace code that was previously spread over several lifecycle methods. 😺 Functional components are less verbose.
  • 5. Let’s look at ⚡️ useState ⚡️ useReducer ⚡️ useEffect ⚡️ useCallback ⚡️ useMemo ⚡️ useRef
  • 7. useState Gotchas / Tips : ✍ Different from setState() of a class component: Does not merge! ✍ If we pass to it a func -> it will run only on the first time ❌ useState(calc(props)) // calc() will run every time ✅ useState(() => calc(props)) ✍ Prefer using the functional way (you’ll be less likely to encounter “Stale State” ).
  • 9. useReducer Tips: ⛰ Use immer to simplify. ⛰ Define the reducer outside of the component (enforce purity).
  • 10. useEffect Purpose: Handle side effects (mostly). How depArr affects behavior: Nothing → Run after each render / Cleanup before every next render [] → Run only after mount / Cleanup before unmount [deps...] → Run only after dependencies change / Cleanup before next render Demo.. Or (named):
  • 11. useEffect: Gotchas / Tips : ✍ beware of one-liners – They might return a value: ❌ ✍ Make sure you define a func for cleanup (instead of calling it): ❌ ⚠️ Do not automatically ignore the ”exhaustive-deps” eslint rule as it may indicate a bug in your code!
  • 12. useEffect: Gotchas / Tips: ✍ useEffect should only have “Stable References” as dependencies: A stable ref is a reference which is constant. Examples: ✅ Consts we define outside the component (props too). ✅ The func returned from useState / useCallback(). ✅ Variables we define with useRef(). ❌ A const defined in a component → it is redefined on each run.
  • 13. useLayoutEffect: In some (rare) cases you'll want to do something synchronously after a render. E.g., read / right to the DOM. Then use useLayoutEffect() instead of useLayoutEffect().
  • 14. useCallback Purpose: Create a memoized function. Useful for passing a funcion as dependency to: ♤ useEffect // otherwise we'll see the 'exhaustive-deps' lint error. ♤ a child component // avoid re-rendring the child on every parent render. Demo..
  • 15. useMemo Purpose: Create a memoized value. ♤ Use as a performance enhancement: In this case the app should work logically the same without it. https://medium.com/javascript-in-plain-english/react-usememo-and-when-you-should-use-it-e69a106bbb02 ♤ Can be used to replace useState + useEffect when useEffect does pure calculations (i.e. no side effects). https://stackoverflow.com/questions/56028913/usememo-vs-useeffect-usestate
  • 16. useRef Purpose: Creates a ”Stable Ref” / ref to the DOM. ♤ Returns an object with the attribute 'current’. ♤ Mutable. ♤ Mutations do not cause a re-render. Demo..
  • 17. useRef Usages examples: ♤ Refer to a DOM element (like createRef() in classes): => Detect clicks outside the element, find its size etc. ♤ Store a mutable value across the lifespan of the component (like placing a value on “this” in a class). => Access a var from different funcs, keep previous state etc. ⚠️ Modify refs in event handlers and effects, not the “render” (=the body of the component).
  • 18. Hooks Rules! 📜 Do not place hooks behind conditions! Make sure all are called every time the component “runs”. Best practice: Place at the top of the component. 📜 Call hooks only from functional components or custom hooks! * Enforced using the eslint-plugin-react-hooks rules.
  • 19. Custom Hooks 🚀 Enable logic reusability between (and within) components. 🚀 Added bonus: Hooks created by the community: → Gists. → Npm packages. * Same hooks rules apply. * The name should start with “use” (otherwise we lose the linter’s help). Demo..
  • 20. Links 📃 The official Docs: https://reactjs.org/docs/hooks-intro.html 📃 Useful hooks (for copy+paste): https://github.com/gragland/usehooks 📃 Useful hooks (as npm packages): https://github.com/gragland/usehooks 📃 Huge collection of hooks related links: https://github.com/rehooks/awesome-react-hooks