Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

React Custom Hooks

//useFetch.js
import { useState, useEffect } from "react";

const useFetch = (url) => {
  const [data, setData] = useState(null);

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

  return [data];
};

export default useFetch;
Comment

Creating with the custom hook in react

import { useState, useEffect } from "react";

const useWindowsWidth = () => {
    const [isScreenSmall, setIsScreenSmall] = useState(false);

    let checkScreenSize = () => {
        setIsScreenSmall(window.innerWidth < 700);
    };

    useEffect(() => {
        checkScreenSize();
        window.addEventListener("resize", checkScreenSize);

        //Cleanup
        return () => window.removeEventListener("resize", checkScreenSize);
    }, []);

    return isSreenSmall;
};

export default useWindowsWidth;
Comment

Custom Hook

function useLocalStorageState(
  key,
  defaulValue,
  { desirialize = JSON.parse, serialize = JSON.stringify } = {}
) {
  const [state, setState] = useState(() => {
    var keyInLocalStorage = window.localStorage.getItem(key);
    if (keyInLocalStorage) {
      try {
        return desirialize(keyInLocalStorage);
      } catch (error) {
        window.localStorage.removeItem(key);
      }
    }

    return typeof defaulValue == "function" ? defaulValue() : defaulValue;
  });

  const prevKeyRef = useRef(key);

  useEffect(() => {
    const prevKey = prevKeyRef.current;

    if (prevKey !== key) {
      window.localStorage.removeItem(prevKey);
    }

    prevKeyRef.current = key;

    window.localStorage.setItem(key, serialize(state));
  }, [key, state, serialize]);

  return [state, setState];
}
Comment

react hooks, react custom hooks

//Go to https://www.30secondsofcode.org/react/ for most commonly 
//used custom hooks and components
Comment

using custom hook

import { useEffect, useState } from "react";
import axios from "axios";
  
function useFetch(url) {
  const [data, setData] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  
  useEffect(() => {
    setLoading(true);
    axios
      .get(url)
      .then((response) => {
        setData(response.data);
      })
      .catch((err) => {
        setError(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [url]);
  
  const refetch = () => {
    setLoading(true);
    axios
      .get(url)
      .then((response) => {
        setData(response.data);
      })
      .catch((err) => {
        setError(err);
      })
      .finally(() => {
        setLoading(false);
      });
  };
  
  return { data, loading, error, refetch };
}
  
export default useFetch;
Comment

custom hook react

//helper>useFetch.jsx
import {useEffect,useState} from 'react'

const useFetch = (url) => {

    const [data,setData] = useState([])

    useEffect(()=>{
      fetch(url).then(res => res.json()).then(data => {
        setData(data);
      }).catch(e=>console.log(e.message));
    },[])
  
  return data
}

export default useFetch

//App.jsx
import useFetch from './helper/useFetch.jsx'
const App = () => {

  const data = useFetch('https://fakestoreapi.com/products')

  return (
    <div>
      {data.map(i => <p key={i.id}>{i.title}</p> )}
    </div>
  )
}

export default App
Comment

React Custom Hooks

//index.js
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

const Home = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((res) => res.json())
      .then((data) => setData(data));
 }, []);

  return (
    <>
      {data &&
        data.map((item) => {
          return <p key={item.id}>{item.title}</p>;
        })}
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Home />);
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript first or default 
Javascript :: how to create variables using javascript 
Javascript :: remove duplicate item from array javascript 
Javascript :: javascript array methods cheat sheet 
Javascript :: javascript function with input value 
Javascript :: fastify query 
Javascript :: quadratic equation in js by function 
Javascript :: signalr 
Javascript :: insertbefore javascript 
Javascript :: how to create my own filter in js 
Javascript :: checks for valid email address syntax javascript 
Javascript :: sveltekit disable ssr 
Javascript :: json parse vs json stringify 
Javascript :: Beep sound Javascript 
Javascript :: Check if a number is even or odd 
Javascript :: macam macam looping javascript 
Javascript :: javascript make pong 
Javascript :: 188.4 - 93.1 
Python :: import keys selenium 
Python :: matplotlib plot dashed 
Python :: check python version colab 
Python :: how to start python quick server 
Python :: change name of pygame window 
Python :: cv2.cvtcolor grayscale 
Python :: download files from google colab 
Python :: ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True site:stackoverflow.com 
Python :: how to add legend to python plot 
Python :: how to make a hidden file in python 
Python :: use incognito mode in selenium webdriver 
Python :: how to install dask in python 
ADD CONTENT
Topic
Content
Source link
Name
4+8 =