DEV Community

Amit Mondal
Amit Mondal

Posted on

3 2

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 👏:

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

nextjs tutorial video

📺 Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay