SlideShare a Scribd company logo
1 of 23
React Hooks Best Practices in 2022
Class-based components previously had access to React capabilities like
state and lifecycle functions. For this reason, function-based
components are called “thin, or purely presentational” since they
cannot access state and lifecycle functions.
Since React Hooks was released, function-based components have
become first-class citizens of React. Moreover, some companies
offering services in React development. Also they provide dedicated
React developers for hiring who can help throughout your
development journey. New methods to compose, reuse, and share
React code has been made possible thanks to function components.
Simple Example of Hook:
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
You clicked {count} times
<button> setCount(count + 1)}&gt;
Click me
</button>
</div>
);
}
After clicking you will get output like below
1. Hooks’ Regulations Should Be Followed
Although it may seem self-evident, both novice and experienced React
developers often fail to observe the following guidelines when using
React hooks:
A. Call Hooks at the Highest Level:
Keep hooks out of loops, nested functions, and conditions. Inside the
hooks, add the conditions you wish to apply to your application.
This should not be done:
if (name !== '') {
useEffect(function persistForm() {
localStorage.setItem('formData', name);
});
}
Instead, do this:
useEffect(function persistForm() {
if (name !== '') {
localStorage.setItem('formData', name);
}
});
All Hooks will be called sequentially when a component is rendered,
thanks to this rule. React is able to do this because of the useState and
use effect functions that enable the state of Hooks to be preserved
appropriately.
B. Only Call Hooks from Function Components:
Regular JavaScript functions should not invoke hooks. Function
components or custom hooks may only be used to call hooks in an
application.
This rule ensures that every stateful logic in a component may be easily
seen in the source code by following this rule.
2. React hooks may benefit from the ESLint plugin
An ESLint plugin for React Hooks has been developed by the React
team and is known as eslint-plugin-react. Before you ever start to
execute your application, this plugin will detect and correct hooks
issues.
It has 2 simples rules:
react-hooks/rules-of-hooks
react-hooks/exhaustive-deps
React-hooks/rules-of-hooks:
function Form() {
// 1. Use the accountName state variable
const [accountName, setAccountName] = useState('David');
// 2. Use an effect for persisting the form
useEffect(function persistForm() {
localStorage.setItem('formData', accountName);
});
// 3. Use the accountDetail state variable
const [accountDetail, setAccountDetail] = useState('Active');
// 4. Use an effect for updating the title
useEffect(function updateStatus() {
document.title = accountName + ' ' + accountDetail;
});
}
React-hooks/exhaustive-deps:
import React, { useState } from "react";
import ReactDOM from "react-dom";
function Account(props) {
const [name, setName] = useState("David");
return;
Hello, {name}! The price is {props.total} and the total amount is {props.amount}
} ReactDOM.render( , document.getElementById('root') );
3. Building function components in order is crucial.
To get the most out of your React application, it’s important to follow
specific rules while creating class components.
Once you’ve called the function Object() { [native code] } and started
your state, you’re ready to go. The component’s job-related functions
come next, followed by the lifecycle functions. When you’re done,
you’ll need to
create the render method.
import React, { useState } from 'react';
const propTypes = {
id: propTypes.number.isRequired,
url: propTypes.string.isRequired,
text: propTypes.string,
};
const defaultProps = {
text: 'Hello World',
};
class Link extends React.Component {
static methodsAreOk() {
return true;
}
constructor(props) {
super(props)
this.state = {
user: null
}
}
componentDidMount() {
console.log('component did mount')
}
componentDidUpdate() {
console.log('component did update')
}
componentWillUnmount() {
console.log('component will unmount')
}
render() {
return {this.props.text}
}
}
Link.propTypes = propTypes
Link.defaultProps = defaultProps
export default Link;
A class component has a built-in function Object() { [native code] } and
a lifecycle function, however function components don’t have these
features:
function App() {
const [user, setUser] = useState(null);
useEffect(() =&gt; {
console.log("component is mounted");
}, []);
const [name, setName] = useState('');
return
<h1>React component order</h1>
;
}
Like class components, it’s important to have a clear structure for your
function components. Once state variables have been declared and
subscriptions have been set up, any appropriate functions may then be
written using useEffect hook.
Finally, you should send back the rendered components to the
browser:
function App() {
const [user, setUser] = useState(null);
const [name, setName] = useState('');
useEffect(() =&gt; {
console.log("component is mounted");
}, []);
return
<h1>React component order</h1>
;
}
4. UseState works just as class component’s state
Declaring multiple variables for each state is common practice in many
useState examples.
const [name, setName] = useState('Liam Walker');
const [email, setEmail] = useState('liamwalker@email.com');
const [age, setAge] = useState(24);
However, useState is able to contain both arrays and objects. It’s still
possible to arrange relevant information together, such as in the
following example:
const [user, setUser] = useState(
{ name: 'Liam', email: 'liamwalker07@email.com', age: 24 }
);
There is, however, a catch. When the useState update function is used
to update the state, the old state is removed and the new one is used
instead. This is not the same as the this of a class component. new
state is combined with old one in setState
const [user, setUser] = useState(
{ name: 'Liam', email: 'liamwalker07@email.com', age: 24 }
);
setUser({ name: 'Lucas' });
// result { name: 'Lucas' }
In order to maintain the prior state, you need to merge it manually by
implementing a callback function that sends the current state value
into it. Given that the user variable provided as state value in the
preceding example, the following argument may be sent to the setUser
function:
setUser((user) = &gt; ({ ...user, name: 'Lucas' }));
// result is { name:'Lucas', email: 'liamwalker@email.com', age: 24 }
Depending on how frequently your application’s data changes, it’s a
good idea to break state into multiple variables.
5. Balance Several useState Requests With a Single
Call to the API
Custom hooks may be used to share functionality across applications.
Some of your application logic will be reused across multiple
components as you create your programme.
Custom hooks allow you to separate your component’s functionality
into reusable functions as described in the next article, which is about
React Hooks.
You may publish your hooks to a single curated collection using Bit
(Github). Using this method, you may install and reuse them in many
apps. A new “hooks library” project isn’t necessary – you can just
“push” new hooks from any project to your shared collection.
Hooks can’t be used in class components, which is the main drawback
to this technique. There are a few options if you still utilize old class
components in your project: you can either turn those components
into functions or use alternative reusable logic patterns (with HOC or
Render Props)
6. Avoid prop drilling with usage
Constantly passing data down from one parent component to another
until it reaches the appropriate child component is known as context
prop drilling in React applications. Other nested components don’t
really require them.
It is possible to transfer data down via the component tree without
having to manually provide props between components using React
Context. The useContext hook allows the child components to make
use of the parent component’s React Context property.
Conclusion:
This is a fantastic addition to the React framework, allowing you to
compose, reuse, and share React code in a manner that was before
impossible. New best practices for building React Hooks are required
since Hooks alter the way developers construct React components, in
order to facilitate development and cooperation across numerous
teams.
Thank you for reading our article. Hope you enjoyed the article. Please
share your ideas with us and do let us know your questions, we are
always here to solve you problems.
Moreover, Bosc Tech has a team of React experts. Contact us for any
need in React development. Do let us know your queries!!!
Content Resource: https://bosctechlabs.com/react-hooks-best-
practices-2022/

More Related Content

Similar to React Hooks Best Practices in 2022.pptx

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 JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 
what is context API and How it works in React.pptx
what is context API and How it works in React.pptxwhat is context API and How it works in React.pptx
what is context API and How it works in React.pptxBOSC Tech Labs
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react jsdhanushkacnd
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryjanet736113
 
Pluginkla2019 - React Presentation
Pluginkla2019 - React PresentationPluginkla2019 - React Presentation
Pluginkla2019 - React PresentationAngela Lehru
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
How to create components in react js
How to create components in react jsHow to create components in react js
How to create components in react jsBOSC Tech Labs
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
Top 10 Techniques For React Performance Optimization in 2022.pptx
Top 10 Techniques For React Performance Optimization in 2022.pptxTop 10 Techniques For React Performance Optimization in 2022.pptx
Top 10 Techniques For React Performance Optimization in 2022.pptxBOSC Tech Labs
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to ReactJean Carlo Emer
 
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
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesWalking Tree Technologies
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today Nitin Tyagi
 
3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS ComponentsSurendra kumar
 

Similar to React Hooks Best Practices in 2022.pptx (20)

react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
Simple React Todo List
Simple React Todo ListSimple React Todo List
Simple React Todo List
 
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 JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
what is context API and How it works in React.pptx
what is context API and How it works in React.pptxwhat is context API and How it works in React.pptx
what is context API and How it works in React.pptx
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react js
 
react-slides.pdf
react-slides.pdfreact-slides.pdf
react-slides.pdf
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react library
 
React
ReactReact
React
 
Pluginkla2019 - React Presentation
Pluginkla2019 - React PresentationPluginkla2019 - React Presentation
Pluginkla2019 - React Presentation
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
How to create components in react js
How to create components in react jsHow to create components in react js
How to create components in react js
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Top 10 Techniques For React Performance Optimization in 2022.pptx
Top 10 Techniques For React Performance Optimization in 2022.pptxTop 10 Techniques For React Performance Optimization in 2022.pptx
Top 10 Techniques For React Performance Optimization in 2022.pptx
 
A full introductory guide to React
A full introductory guide to ReactA full introductory guide to React
A full introductory guide to React
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 
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...
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
 
3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components
 

More from BOSC Tech Labs

Guide 101_ Material Design in Android App Development.pdf
Guide 101_ Material Design in Android App Development.pdfGuide 101_ Material Design in Android App Development.pdf
Guide 101_ Material Design in Android App Development.pdfBOSC Tech Labs
 
How do you hire a skilled Android developer for your project_.pdf
How do you hire a skilled Android developer for your project_.pdfHow do you hire a skilled Android developer for your project_.pdf
How do you hire a skilled Android developer for your project_.pdfBOSC Tech Labs
 
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdf
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdfGuide to 2024’s Elite Software Developers by MobileAppDaily.pdf
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdfBOSC Tech Labs
 
How to build a live chat widget in React_.pdf
How to build a live chat widget in React_.pdfHow to build a live chat widget in React_.pdf
How to build a live chat widget in React_.pdfBOSC Tech Labs
 
How to hire ios app development experts for your next project_.pdf
How to hire ios app development experts for your next project_.pdfHow to hire ios app development experts for your next project_.pdf
How to hire ios app development experts for your next project_.pdfBOSC Tech Labs
 
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdfSwiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdfBOSC Tech Labs
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdfBOSC Tech Labs
 
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...BOSC Tech Labs
 
The Role iOS App Development_ Hiring for the Future.pdf
The Role iOS App Development_ Hiring for the Future.pdfThe Role iOS App Development_ Hiring for the Future.pdf
The Role iOS App Development_ Hiring for the Future.pdfBOSC Tech Labs
 
React 19: Revolutionizing Web Development
React 19: Revolutionizing Web DevelopmentReact 19: Revolutionizing Web Development
React 19: Revolutionizing Web DevelopmentBOSC Tech Labs
 
2024 Custom Software Development Guide: Trends, Steps & Benefits
2024 Custom Software Development Guide: Trends, Steps & Benefits2024 Custom Software Development Guide: Trends, Steps & Benefits
2024 Custom Software Development Guide: Trends, Steps & BenefitsBOSC Tech Labs
 
What is the Easiest Way to Hire a React Developer?
What is the Easiest Way to Hire a React Developer?What is the Easiest Way to Hire a React Developer?
What is the Easiest Way to Hire a React Developer?BOSC Tech Labs
 
Top 10 React Carousel Component Libraries and their Usage Trends
Top 10 React Carousel Component Libraries and their Usage TrendsTop 10 React Carousel Component Libraries and their Usage Trends
Top 10 React Carousel Component Libraries and their Usage TrendsBOSC Tech Labs
 
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...BOSC Tech Labs
 
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERSSTEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERSBOSC Tech Labs
 
Top 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React DeveloperTop 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React DeveloperBOSC Tech Labs
 
Transform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPTTransform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPTBOSC Tech Labs
 
Which Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdfWhich Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdfBOSC Tech Labs
 
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...BOSC Tech Labs
 
Boost Your Website with Top React Carousel Libraries | BOSC
Boost Your Website with Top React Carousel Libraries | BOSCBoost Your Website with Top React Carousel Libraries | BOSC
Boost Your Website with Top React Carousel Libraries | BOSCBOSC Tech Labs
 

More from BOSC Tech Labs (20)

Guide 101_ Material Design in Android App Development.pdf
Guide 101_ Material Design in Android App Development.pdfGuide 101_ Material Design in Android App Development.pdf
Guide 101_ Material Design in Android App Development.pdf
 
How do you hire a skilled Android developer for your project_.pdf
How do you hire a skilled Android developer for your project_.pdfHow do you hire a skilled Android developer for your project_.pdf
How do you hire a skilled Android developer for your project_.pdf
 
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdf
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdfGuide to 2024’s Elite Software Developers by MobileAppDaily.pdf
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdf
 
How to build a live chat widget in React_.pdf
How to build a live chat widget in React_.pdfHow to build a live chat widget in React_.pdf
How to build a live chat widget in React_.pdf
 
How to hire ios app development experts for your next project_.pdf
How to hire ios app development experts for your next project_.pdfHow to hire ios app development experts for your next project_.pdf
How to hire ios app development experts for your next project_.pdf
 
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdfSwiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
 
The Role iOS App Development_ Hiring for the Future.pdf
The Role iOS App Development_ Hiring for the Future.pdfThe Role iOS App Development_ Hiring for the Future.pdf
The Role iOS App Development_ Hiring for the Future.pdf
 
React 19: Revolutionizing Web Development
React 19: Revolutionizing Web DevelopmentReact 19: Revolutionizing Web Development
React 19: Revolutionizing Web Development
 
2024 Custom Software Development Guide: Trends, Steps & Benefits
2024 Custom Software Development Guide: Trends, Steps & Benefits2024 Custom Software Development Guide: Trends, Steps & Benefits
2024 Custom Software Development Guide: Trends, Steps & Benefits
 
What is the Easiest Way to Hire a React Developer?
What is the Easiest Way to Hire a React Developer?What is the Easiest Way to Hire a React Developer?
What is the Easiest Way to Hire a React Developer?
 
Top 10 React Carousel Component Libraries and their Usage Trends
Top 10 React Carousel Component Libraries and their Usage TrendsTop 10 React Carousel Component Libraries and their Usage Trends
Top 10 React Carousel Component Libraries and their Usage Trends
 
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
 
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERSSTEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
 
Top 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React DeveloperTop 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React Developer
 
Transform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPTTransform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPT
 
Which Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdfWhich Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdf
 
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
 
Boost Your Website with Top React Carousel Libraries | BOSC
Boost Your Website with Top React Carousel Libraries | BOSCBoost Your Website with Top React Carousel Libraries | BOSC
Boost Your Website with Top React Carousel Libraries | BOSC
 

Recently uploaded

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 

Recently uploaded (20)

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 

React Hooks Best Practices in 2022.pptx

  • 1.
  • 2. React Hooks Best Practices in 2022 Class-based components previously had access to React capabilities like state and lifecycle functions. For this reason, function-based components are called “thin, or purely presentational” since they cannot access state and lifecycle functions. Since React Hooks was released, function-based components have become first-class citizens of React. Moreover, some companies offering services in React development. Also they provide dedicated React developers for hiring who can help throughout your development journey. New methods to compose, reuse, and share React code has been made possible thanks to function components.
  • 3. Simple Example of Hook: import React, { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); return ( <div> You clicked {count} times <button> setCount(count + 1)}&gt; Click me </button> </div> ); }
  • 4. After clicking you will get output like below
  • 5. 1. Hooks’ Regulations Should Be Followed Although it may seem self-evident, both novice and experienced React developers often fail to observe the following guidelines when using React hooks: A. Call Hooks at the Highest Level: Keep hooks out of loops, nested functions, and conditions. Inside the hooks, add the conditions you wish to apply to your application. This should not be done:
  • 6. if (name !== '') { useEffect(function persistForm() { localStorage.setItem('formData', name); }); } Instead, do this: useEffect(function persistForm() { if (name !== '') { localStorage.setItem('formData', name); } });
  • 7. All Hooks will be called sequentially when a component is rendered, thanks to this rule. React is able to do this because of the useState and use effect functions that enable the state of Hooks to be preserved appropriately. B. Only Call Hooks from Function Components: Regular JavaScript functions should not invoke hooks. Function components or custom hooks may only be used to call hooks in an application. This rule ensures that every stateful logic in a component may be easily seen in the source code by following this rule.
  • 8. 2. React hooks may benefit from the ESLint plugin An ESLint plugin for React Hooks has been developed by the React team and is known as eslint-plugin-react. Before you ever start to execute your application, this plugin will detect and correct hooks issues. It has 2 simples rules: react-hooks/rules-of-hooks react-hooks/exhaustive-deps
  • 9. React-hooks/rules-of-hooks: function Form() { // 1. Use the accountName state variable const [accountName, setAccountName] = useState('David'); // 2. Use an effect for persisting the form useEffect(function persistForm() { localStorage.setItem('formData', accountName); }); // 3. Use the accountDetail state variable const [accountDetail, setAccountDetail] = useState('Active'); // 4. Use an effect for updating the title useEffect(function updateStatus() { document.title = accountName + ' ' + accountDetail; }); }
  • 10. React-hooks/exhaustive-deps: import React, { useState } from "react"; import ReactDOM from "react-dom"; function Account(props) { const [name, setName] = useState("David"); return; Hello, {name}! The price is {props.total} and the total amount is {props.amount} } ReactDOM.render( , document.getElementById('root') );
  • 11. 3. Building function components in order is crucial. To get the most out of your React application, it’s important to follow specific rules while creating class components. Once you’ve called the function Object() { [native code] } and started your state, you’re ready to go. The component’s job-related functions come next, followed by the lifecycle functions. When you’re done, you’ll need to create the render method.
  • 12. import React, { useState } from 'react'; const propTypes = { id: propTypes.number.isRequired, url: propTypes.string.isRequired, text: propTypes.string, }; const defaultProps = { text: 'Hello World', }; class Link extends React.Component { static methodsAreOk() { return true; } constructor(props) { super(props) this.state = { user: null } }
  • 13. componentDidMount() { console.log('component did mount') } componentDidUpdate() { console.log('component did update') } componentWillUnmount() { console.log('component will unmount') } render() { return {this.props.text} } } Link.propTypes = propTypes Link.defaultProps = defaultProps export default Link;
  • 14. A class component has a built-in function Object() { [native code] } and a lifecycle function, however function components don’t have these features: function App() { const [user, setUser] = useState(null); useEffect(() =&gt; { console.log("component is mounted"); }, []); const [name, setName] = useState(''); return <h1>React component order</h1> ; }
  • 15. Like class components, it’s important to have a clear structure for your function components. Once state variables have been declared and subscriptions have been set up, any appropriate functions may then be written using useEffect hook. Finally, you should send back the rendered components to the browser: function App() { const [user, setUser] = useState(null); const [name, setName] = useState(''); useEffect(() =&gt; { console.log("component is mounted"); }, []); return <h1>React component order</h1> ; }
  • 16. 4. UseState works just as class component’s state Declaring multiple variables for each state is common practice in many useState examples. const [name, setName] = useState('Liam Walker'); const [email, setEmail] = useState('liamwalker@email.com'); const [age, setAge] = useState(24); However, useState is able to contain both arrays and objects. It’s still possible to arrange relevant information together, such as in the following example:
  • 17. const [user, setUser] = useState( { name: 'Liam', email: 'liamwalker07@email.com', age: 24 } ); There is, however, a catch. When the useState update function is used to update the state, the old state is removed and the new one is used instead. This is not the same as the this of a class component. new state is combined with old one in setState const [user, setUser] = useState( { name: 'Liam', email: 'liamwalker07@email.com', age: 24 } ); setUser({ name: 'Lucas' }); // result { name: 'Lucas' }
  • 18. In order to maintain the prior state, you need to merge it manually by implementing a callback function that sends the current state value into it. Given that the user variable provided as state value in the preceding example, the following argument may be sent to the setUser function: setUser((user) = &gt; ({ ...user, name: 'Lucas' })); // result is { name:'Lucas', email: 'liamwalker@email.com', age: 24 } Depending on how frequently your application’s data changes, it’s a good idea to break state into multiple variables.
  • 19. 5. Balance Several useState Requests With a Single Call to the API Custom hooks may be used to share functionality across applications. Some of your application logic will be reused across multiple components as you create your programme. Custom hooks allow you to separate your component’s functionality into reusable functions as described in the next article, which is about React Hooks.
  • 20. You may publish your hooks to a single curated collection using Bit (Github). Using this method, you may install and reuse them in many apps. A new “hooks library” project isn’t necessary – you can just “push” new hooks from any project to your shared collection. Hooks can’t be used in class components, which is the main drawback to this technique. There are a few options if you still utilize old class components in your project: you can either turn those components into functions or use alternative reusable logic patterns (with HOC or Render Props)
  • 21. 6. Avoid prop drilling with usage Constantly passing data down from one parent component to another until it reaches the appropriate child component is known as context prop drilling in React applications. Other nested components don’t really require them. It is possible to transfer data down via the component tree without having to manually provide props between components using React Context. The useContext hook allows the child components to make use of the parent component’s React Context property.
  • 22. Conclusion: This is a fantastic addition to the React framework, allowing you to compose, reuse, and share React code in a manner that was before impossible. New best practices for building React Hooks are required since Hooks alter the way developers construct React components, in order to facilitate development and cooperation across numerous teams.
  • 23. Thank you for reading our article. Hope you enjoyed the article. Please share your ideas with us and do let us know your questions, we are always here to solve you problems. Moreover, Bosc Tech has a team of React experts. Contact us for any need in React development. Do let us know your queries!!! Content Resource: https://bosctechlabs.com/react-hooks-best- practices-2022/