React Hook practice example

Young Han
1 min readMay 12, 2021

This project is that when users click the button, fetched Gif API and shows gifs.

React can shows items without a search button or click the search button. I think click search button need more step than showing items without clicking the search button. So I tried to make it by clicking the search button.

First, npx creact-react-app ./

seconds, import { useEffect, useState } from “react”;

I will use react hook, so I need useEffect and useState.

const [gifs, setGifs] = useState([]);const [search, setSearch] = useState("");const [query, setQuery] = useState("");

This for the fetched gifs pictures, searched item, and query for submit button.

useEffect(() => {fetch(URL).then((res) => res.json()).then((data) => setGifs(data.data));}, [URL]);

I used useEffect for fetching gifs.

<form action="submit" onSubmit={(e) => searchItems(e)}><inputtype="text"defaultValue={search}onChange={(e) => setSearch(e.target.value)}/><button>search</button></form>

This part for clicking submits button and updated state.

const searchItems = (e) => {e.preventDefault();setQuery(e.target.childNodes[0].value);};

Now, this function will update the gifs state and will show items.

Github final code: https://github.com/yhan0704/Gifs-React-Mini-Project/blob/main/src/App.js

--

--