Techumber
Home Blog Work

Understanding the Basics of React Hooks

Published on July 25, 2020

Introduction

React Hooks are a powerful tool for managing state and side effects in React components. In this post, we will explore the basics of React Hooks and how they can be used to simplify your code and make it more maintainable.

What is a React Hook?

A React Hook is a function that allows you to extract logic from a component and reuse it across your application. This makes it easier to manage state and side effects, and can also help to keep your components focused on the task at hand.

There are several types of React Hooks available, including useState, useEffect, and useContext. Each of these hooks has its own specific use case and behavior, so it’s important to understand when to use each one.

Use State

One of the most common uses for React Hooks is to manage state. The useState hook allows you to create a state variable that can be accessed and updated within your component. This makes it easy to keep track of changes in your application, and can also help to simplify complex conditional statements.

Here’s an example of how you might use the useState hook:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You have clicked the button {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

In this example, we are creating a state variable called count that starts at 0. We are also creating a function called setCount that updates the value of count. Whenever the user clicks the button, the setCount function is called with an updated value, and the component will re-render to display the new count.

Use Effect

Another common use case for React Hooks is managing side effects. A side effect is any operation that has a side effect on your application or data, such as making an API call or updating the DOM. The useEffect hook allows you to perform side effects in a consistent and predictable way within your component.

Here’s an example of how you might use the useEffect hook:

import React, { useState, useEffect } from 'react';

function FetchData() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then((response) => response.json())
      .then((data) => setData(data));
  }, []);

  return (
    <div>
      <p>{data ? `You have clicked the button ${data.count} times` : 'Loading...'}</p>
      <button onClick={() => fetch('https://api.example.com/data')}>Click me</button>
    </div>
  );
}

In this example, we are using the useEffect hook to make an API call when the component mounts (i.e., when it is first rendered). The hook takes two arguments: a function that will be called after the component has mounted, and an array of dependencies that determine when the hook should be re-run. In this case, we are only fetching data from the API once, so we pass an empty array as the second argument to ensure that the hook is only run once.

Whenever the user clicks the button, a new API call will be made and the component will re-render with the updated data.

Use Context

The useContext hook allows you to access context from within a functional component. This can be useful when you need to share data or state between different parts of your application.

Here’s an example of how you might use the useContext hook:

import React, { useState, useContext } from 'react';

const MyContext = createContext();

function App() {
  const [data, setData] = useState(null);

  return (
    <div>
      <MyContext.Provider value={{ data }}>
        <ChildComponent />
      </MyContext.Provider>
    </div>
  );
}

function ChildComponent() {
  const { data } = useContext(MyContext);

  return (
    <div>
      <p>{data ? `You have clicked the button ${data.count} times` : 'Loading...'}</p>
      <button onClick={() => setData({ count: data.count + 1 })}>Click me</button>
    </div>
  );
}

In this example, we are creating a context called MyContext that stores an object with the current value of data. We are then using the useState hook to create a state variable called data, and passing it as a prop to our ChildComponent. Within the ChildComponent, we are using the useContext hook to access the context and retrieve the value of data.

Whenever the user clicks the button, the setData function will be called with an updated object, and the component will re-render with the new data.

Conclusion

React Hooks are a powerful tool for managing state and side effects in React components. By using these hooks, you can simplify your code, make it more maintainable, and keep your components focused on the task at hand. Whether you’re working with simple state variables or complex side effects, React Hooks have got you covered.