If you're new to React, you might be wondering what React Hooks are and when you should use them. React only introduced hooks in its 16.8 release but they have quickly become an essential feature of the library.

Learn all about the basics of React Hooks and discover some best practices for using them in your React applications.

What Are React Hooks?

React Hooks let you use state and other React features without writing extra code. Hooks are a great way to make your code more readable and maintainable.

There are a few different Hooks in React, but the most commonly used are useState and useEffect. The useState hook lets you add state to your components. This is useful for things like keeping track of a user's input or changes to a form. The useEffect hook lets you run a function whenever a component renders. This is useful for things like fetching data from an API or setting up a subscription.

When Should You Use React Hooks?

You should use React Hooks whenever you need to add extra functionality to a component. For example, if you need to keep track of a user's input, you would use the useState hook. If you need to fetch data from an API, you would use the useEffect hook. You can also create custom hooks for API calls.

If you just started using React, you might not need to use Hooks yet. But as you build more complex apps, you'll find that Hooks are a great way to add extra functionality to your components.

Best Practices With React Hooks

Now that you know what React Hooks are and when to use them, let's talk about some best practices.

1. Only Call Hooks From React Functions

You should only call React Hooks from React functions. If you try to call react hooks from a class component, you'll get an error.

This is because you can only call a React Hook from a React function. React functions are components that you declare with a function keyword.

Here's an example of a React function component:

        import React, { useState } from 'react';
 
function App() {
  const [count, setCount] = useState(0);
 
  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

And here's an example of a class component:

        import React, { Component } from 'react';
 
class App extends Component {
  state = {
    count: 0
  };
 
  render() {
    return (
      <div>
        <p>{this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

The first example declares the App component using the function keyword, while the second uses the class keyword.

2. Use Only One useEffect Hook

If you're using the useEffect hook, you should only use one per component. This is because useEffect runs whenever a component renders.

If you have multiple useEffect hooks, they will all run whenever a component renders. This can lead to unexpected behavior and performance problems. In the below example, both useEffects will run whenever the App component renders.

        import React, { useState, useEffect } from 'react';
 
function App() {
  const [count, setCount] = useState(0);
 
  useEffect(() => {
    console.log('This will run whenever the App component renders!');
  }, []);
 
  useEffect(() => {
    console.log('This will also run whenever the App component renders!');
  }, []);
 
  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Instead of using multiple useEffect hooks, you can use a single useEffect hook and put all of your code inside it. In the below example, only one useEffect hook will run whenever the App component renders.

        import React, { useState, useEffect } from 'react';
 
function App() {
  const [count, setCount] = useState(0);
 
  useEffect(() => {
    console.log('This will run whenever the App component renders!');
    console.log('This will also run whenever the App component renders!');
  }, []);
 
  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

This means that you can only call React Hooks from the first example. If you try to call React Hooks from the second example, you'll get an error.

3. Use Hooks at the Top Level

One of the best practices with React Hooks is to use them at the top level. You should avoid using hooks inside loops, conditions, or nested functions. For example, if you useState inside a for loop, each time the loop runs, React will create a new state variable. This can lead to unexpected behavior.

        import React, { useState } from 'react';
 
function App() {
  for (let i = 0; i < 10; i++) {
    // Don't do this!
    const [count, setCount] = useState(0);
  }
 
  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In the above example, the App component will only ever render the count and button from the final iteration of the loop. This is because React only updates the state variable from the last iteration.

Instead of usingState inside a loop, you can declare a state variable outside of the loop. This way, React will only create one state variable and update it accordingly.

        import React, { useState } from 'react';
 
function App() {
  // This is the correct way to use useState inside a loop
  const [count, setCount] = useState(0);
 
  for (let i = 0; i < 10; i++) {
    // ...
  }
 
  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

4. Don’t Overuse Hooks

React Hooks are a powerful tool, but you should avoid overusing them. If you find yourself using multiple Hook in every component, you might be overusing them.

React Hooks are most useful when you need to share state between multiple components. Avoid using unnecessary Hooks because they can make your code hard to read, and they might affect performance if used excessively.

Add More Functionality Using React 18 Hooks

With the release of React 18, there are new hooks available. Each hook is specific to a certain React feature. You can find a list of all the available hooks on the React website. But the most commonly used hooks are still useState and useEffect.