DEV Community

Cover image for 2 React Hooks That Every Beginner Should Know
KevinZ-CS
KevinZ-CS

Posted on

2 React Hooks That Every Beginner Should Know

A React Hook is a JavaScript function that lets you "hook into" React state and lifecycle features from functional components. It was first introduced in React 16.8 and provides an alternative to writing class-based components. While legacy projects use class components, most of modern React development uses functional components which utilizes hooks that allows developers to write clearer and more concise code.

In this blog post we will be going over 2 useful hooks that every beginner should know when first learning React. Namely, the State Hook and Effect Hook will be covered below.

State Hook

In React, a state is a piece of data that is dynamic within a component. It stores data that is subject to change based on how users interact with the application. Below is an example of how a state is initiated in React and how it can be used in a component.

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

To initiate a React state we first import the useState function and then call the function while passing in an initial state (initial value in this case is 0). This function call will return an array with 2 elements with the first being the value of the initial state and the second being a function used to update the state. We then de-structure the array creating 2 new variables that can readily be used in our component. The count variable contains the current state while the setCount variable contains the function that updates the current state.

In this case we are updating the state through the onClick event handler. Every time the user clicks on the button, 1 gets added to the current state and that new value gets passed into the setCount function which updates the current state to the new value. So with an initial state of 0, after clicking the button one time the current state updates to 1 since 1 + 0 = 1. As soon as the state updates, the entire component re-renders and new state of 1 will be reflected within the p tag and displayed to the user.

Effect Hook

The Effect Hook is a React hook that causes a side effect when the component renders. It looks something like this:

import React, { useEffect } from "react";

function DogPics() {
  const [images, setImages] = useState([]);

  useEffect(() => {
    fetch("https://dog.ceo/api/breeds/image/random/3")
      .then((r) => r.json())
      .then((data) => {
        // setting state in the useEffect callback
        setImages(data.message);
      });
  });

  return (
    <div>
      {images.map((image) => (
        <img src={image} key={image} />
      ))}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

To initiate the hook we first import the useEffect function from the React library and then we call it while passing in a callback function. UseEffect will then be called when the component renders and the side effect will be based on the callback function that was passed in. A common use for useEffect is fetching data from an API and storing it in a state when the component renders.

As shown in the above code block, when the component loads a fetch request is made to the dog API, which ultimately resolves to a response object that is parsed as JSON and finally stored in the images state by calling setImages. This state is then used in the returned JSX which will be displayed to the user. From the user perspective, all the individual will see is a dog image displayed when they first load the webpage.

However, the way useEffect is currently written above, it will eventually result in an error. The reason being that we did not pass in a second argument called a dependency array. A dependency array allows us to control when useEffect gets called. In the above example, because we did not pass in a dependency array, useEffect will be called continuously which will result in an endless loop of fetch requests. This will eventually lead to the API kicking us out for hitting the rate limit.

A solution to this is passing in an empty dependency array like so:

import React, { useEffect } from "react";

function DogPics() {
  const [images, setImages] = useState([]);

  useEffect(() => {
    fetch("https://dog.ceo/api/breeds/image/random/3")
      .then((r) => r.json())
      .then((data) => {
        // setting state in the useEffect callback
        setImages(data.message);
      });
  }, [] ); // added empty dependency array

  return (
    <div>
      {images.map((image) => (
        <img src={image} key={image} />
      ))}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

By including an empty dependency array as a second argument to useEffect, useEffect will only be called when the component first mounts. This will prevent an endless loop of fetch requests and will only fetch the data once when the component first loads.

Another way to control when useEffect gets called is passing in a state into the dependency array like so:

import React, { useEffect } from "react";

function DogPics() {
  const [images, setImages] = useState([]);

  useEffect(() => {
    fetch("https://dog.ceo/api/breeds/image/random/3")
      .then((r) => r.json())
      .then((data) => {
        // setting state in the useEffect callback
        setImages(data.message);
      });
  }, [images] ); // added images state dependency array

  return (
    <div>
      {images.map((image) => (
        <img src={image} key={image} />
      ))}
    </div>
  );
}
Note: Although adding the images state in the dependency array in this context does not logically make sense, this is purely for demonstration purposes.
Enter fullscreen mode Exit fullscreen mode

Using the same block of code we've been using, we've now passed in the images state to the dependency array. So now useEffect will be called when the component first mounts and will subsequently be called again if the state in the dependency array updates. So in our case after useEffect is called when the component first mounts, it will be called again if the images state is ever updated.

Conclusion

Fetching data from an API when a website first loads and storing it in some type of variable are basic concepts that all new developers should be familiar with. Both the State and Effect Hook help simplify this process which shows the effectiveness and efficiency of React hooks. As developers we will come across many other hooks that will assist us in our React development but should keep in mind of two general rules that should be followed when it comes to React hooks.

  1. Only call Hooks at the tope level.
  2. Only call Hooks from React function components.

For more information on hooks or React in general you can always refer to their documentation on their website.

Good Luck!

Resources

https://reactjs.org/docs/hooks-overview.html

Top comments (0)