React Hooks Best Practices in 2022
Tags: react, hooks, programming, bestpractices
Published: 2022-05-19 11:08:16

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 hire 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**

```javascript
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)}
Click me
</button>
 
</div>
);
}
```
**Output:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tp4z5q4p1fotw8h4mc8q.png)
After Clicking You Will Get Output Like Below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jqsl9fc6dppa70vroel1.png)
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:

 

```javascript
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 useEffect’s 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 doesn’t appear in the dependencies array

**React-hooks/rules-of-hooks:**

```javascript
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') );
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hkg65rnqs8jhozruhddh.png)
##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.

 

```javascript
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:

 

```javascript
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
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:

```javascript
function App() {
const [user, setUser] = useState(null);
const [name, setName] = useState('');
useEffect(() => {
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 component’s state
Declaring multiple variables for each state is common practice in many useState examples.

```javascript
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:

```javascript
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

```javascript
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:

```javascript
setUser((user) => ({ ...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.

As a rule of thumb, it’s best to keep each state separate so that it’s 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 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!!!