reading-notes


Project maintained by Razan-am Hosted on GitHub Pages — Theme by mattgraham

Context API

Describe use cases useState() vs useReducer()

Why do custom hooks need the use prefix?

What do custom hooks usually do?

Using any list of custom hooks, research and name one that you think will be useful in your applications

useForm

Describe how a hook that fetches API data might work

  1. Import useEffect
    • import React, { useEffect } from "react"
  2. Then, define your useEffect hook inside of your component. import React, { useEffect } from “react”;

     const App = () => {
            
         useEffect(() => {
    
         }, []);
    
         return <div></div>;
     };
    
    export default App;
    
  3. Define your URL

     useEffect(() => {
    
         const url = "https://api.adviceslip.com/advice"
            
     }, []);
    

4.Create the asynchronous function

const fetchData = async () => {

    try {
        const response = await fetch(url);
        const json = await response.json();
        console.log(json);
        } catch (error) {
        console.log("error", error);
        }
};
  1. Put the fetchData function above in the useEffect hook and call it, like so:

     useEffect(() => {
         const url = "https://api.adviceslip.com/advice";
    
         const fetchData = async () => {
         try {
             const response = await fetch(url);
             const json = await response.json();
             console.log(json);
         } catch (error) {
             console.log("error", error);
         }
         };
    
         fetchData();
     }, []);
    

The function we just created is wrapped in a try…catch statement so that the function catches the errors and prints them in the console. This helps debug and prevents the app to crash unexpectedly.


Terms


context api

When to Use Context

Before You Use Context

API


References:

@By wix engineering/Custom React Hook: When Software Design Meets React Hooks

@By Toby Rogers/Top 10 Custom React Hooks you Should Have in Your Toolbox

@By designcode/Fetch Data from an API