DEV Community

Amit Mondal
Amit Mondal

Posted on

Simple use of ⚛️React useState Hook

Just an ordinary day and was jumping around videos on YouTube and came across a short video tutorial on creating a react app that uses the Advice Slip API. It is a pretty easy and quick example but in this tutorial react's class component was used to make the app.

So I thought let's re-develop it using the latest React Hooks, so used the useState hook of React v16.8 to re-implement the app.

Live Demo

Codesandbox Link

Following is the code:

File: App.js

// Importing useState from react
import React, { useState } from "react";
import "./styles.css";

export default function App() {
  /**
   * We declare a new state variable(advice) by calling the useState Hook,
   * and set it to ''(empty string) initially.
   * React will remember its current value between re-renders,
   * and provide the most recent one to our function.
   * If we want to update the current advice, we can call setAdvice.
   */

  const [advice, setAdvice] = useState("");

  const fetchAdvice = () => {
    const adviceAPI = "https://api.adviceslip.com/advice";

    // Fetch a random advice slip
    fetch(adviceAPI)
      .then(response => response.json())
      .then(data => {
        // destructuring the advice from data
        const { advice } = data.slip;

        // update to new advice we just fetched
        setAdvice(advice);
      })
      .catch(error => console.error(`Error: ${error}`));
  };

  return (
    <div className="app">
      <div className="card">
        <h2 className="heading">{advice}</h2>
        {/* Trigger fetchAdvice on button click */}
        <button className="button" onClick={fetchAdvice}>
          <span>GIVE ME ADVICE!</span>
        </button>
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

File: styles.css If you want to decorate it a bit.

body {
  background-color: #666;
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  background-color: #999;
  max-width: 500px;
  padding: 12px;
  margin: auto;
  text-align: center;
  font-family: arial;
}

.card button {
  border: none;
  outline: 0;
  padding: 12px;
  color: white;
  background-color: #000;
  text-align: center;
  cursor: pointer;
  width: 60%;
  font-size: 18px;
}

.card button:hover {
  opacity: 0.7;
}
Enter fullscreen mode Exit fullscreen mode

Credits

This is a re-implementation of Adrian Hajdin's work 👏:

Top comments (0)