Techumber
Home Blog Work

Getting Started with React Hooks

Published on July 24, 2020

Introduction

In this post, we will explore React Hooks and how they can be used to manage state and side effects in React components. We will start with the basics and then move on to more advanced topics…

React Hooks are a powerful way to manage state and side effects in React components. With Hooks, you can extract logic from components and reuse it across your application. This makes your code more modular and maintainable. In this post, we will explore how to use React Hooks in your own applications.

Stateful Logic with UseState()

The most common use case for Hooks is managing state. You can create a state variable using the useState() hook, which returns an array with the current value and a function to update it. Here’s an example:

import React from "react";

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

In this example, we define a Counter component that renders a button and a paragraph with the current count. When the button is clicked, it updates the state using the setCount() function. The useState() hook returns an array with the current value of count (0) and a function to update it (setCount).

Side Effects with UseEffect()

Another common use case for Hooks is managing side effects, such as fetching data from an API or setting up event listeners. You can use the useEffect() hook to execute code after rendering. Here’s an example:

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

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

In this example, we define a useEffect() hook that fetches data from an API and logs it to the console. The second argument of useEffect() is an empty array ([]), which means that this effect will only run once, when the component mounts. We can use this technique to set up event listeners or perform other side effects that need to happen only once in the lifecycle of a component.

Custom Hooks with useReducer() and useContext()

React provides two other Hooks for more advanced state management: useReducer() and useContext(). These Hooks allow you to manage complex state logic using a reducer function or a context object, respectively. Here’s an example of using useReducer():

import React from "react";
import { useReducer } from "react";

function Counter() {
  const [count, dispatch] = useReducer((state, action) => {
    switch (action.type) {
      case "increment":
        return state + 1;
      case "decrement":
        return state - 1;
      default:
        throw new Error();
    }
  }, 0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>Increment</button>
      <button onClick={() => dispatch({ type: "decrement" })}>Decrement</button>
    </div>
  );
}

In this example, we define a Counter component that uses the useReducer() hook to manage its state. The reducer function takes two arguments: the current state and an action object. We use a switch statement to determine which type of action was dispatched and update the state accordingly.

Conclusion

React Hooks are a powerful way to manage state and side effects in React components. With Hooks, you can extract logic from components and reuse it across your application. This makes your code more modular and maintainable. In this post, we explored the basics of using useState(), useEffect(), and useReducer() to manage state and side effects in React components. We also covered how to use custom Hooks like useContext().

Conclusion

React Hooks are a powerful way to manage state and side effects in React components. With Hooks, you can extract logic from components and reuse it across your application. This makes your code more modular and maintainable. In this post, we explored the basics of using useState(), useEffect(), and useReducer() to manage state and side effects in React components. We also covered how to use custom Hooks like useContext().

Example of a React component using hooks

In this example, we define a Counter component that uses the useReducer() hook to manage its state. The reducer function takes two arguments: the current state and an action object. We use a switch statement to determine which type of action was dispatched and update the state accordingly.