Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 19, 2022 11:08 am GMT

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>);}

Output:

Image description
After Clicking You Will Get Output Like Below:

Image description
In this piece, we will provide you with six strategies for using React Hooks in your components:

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
The first rule simply compels your code to comply with the requirements of hooks. To ensure that the useEffects rule is being adhered to, exhaustive-deps is employed.

Exhaustive-deps warnings may be triggered by the following userInfo component because the useEffect uses the userId variable but it doesnt appear in the dependencies array

React-hooks/rules-of-hooks:

function Form() {// 1. Use the accountName state variableconst [accountName, setAccountName] = useState('David');// 2. Use an effect for persisting the formuseEffect(function persistForm() {localStorage.setItem('formData', accountName);});// 3. Use the accountDetail state variableconst [accountDetail, setAccountDetail] = useState('Active');// 4. Use an effect for updating the titleuseEffect(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') );

Image description

3. Building function components in order is crucial.

To get the most out of your React application, its important to follow specific rules while creating class components.

Once youve called the function Object() { [native code] } and started your state, youre ready to go. The components job-related functions come next, followed by the lifecycle functions. When youre done, youll 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 = propTypesLink.defaultProps = defaultPropsexport default Link;

A class component has a built-in function Object() { [native code] } and a lifecycle function, however function components dont 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, its 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>;}

Your code will be easier to read and understand if you enforce a logical structure.

4. UseState works just as class components state

Declaring multiple variables for each state is common practice in many useState examples.

const [name, setName] = useState('Liam Walker');const [email, setEmail] = useState('[email protected]');const [age, setAge] = useState(24);

However, useState is able to contain both arrays and objects. Its still possible to arrange relevant information together, such as in the following example:

const [user, setUser] = useState({ name: 'Liam', email: '[email protected]', 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: '[email protected]', 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: '[email protected]', age: 24 }

Depending on how frequently your applications data changes, its a good idea to break state into multiple variables.

As a rule of thumb, its best to keep each state separate so that its easy to update and submit the data.

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 components 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 isnt necessary you can just push new hooks from any project to your shared collection.

Hooks cant 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 dont 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 components 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!!!


Original Link: https://dev.to/kuldeeptarapara/react-hooks-best-practices-in-2022-4bh0

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To