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 :: build json object 
Javascript :: spring boot map json to object in controller 
Javascript :: array length 
Javascript :: find consecutive numbers in an array javascript 
Javascript :: javascript check string empty 
Javascript :: phaser3 align text center 
Javascript :: random between min and max 
Javascript :: Fetch Data Using Getx 
Javascript :: use obj property inside itself 
Javascript :: how to call api on load using hooks in react 
Javascript :: push notification react native 
Javascript :: jstree expend all node 
Javascript :: Ocultar un elemento cuando la ventana cambia de tamaño css 
Javascript :: SHOPIFY COUNTRY SELECTOR 
Javascript :: Find the Longest Word in a String 
Javascript :: script defer attribute 
Javascript :: javascript window location 
Javascript :: react write into json file 
Javascript :: mongoose connections 
Javascript :: prettier overrides 
Javascript :: foreach js 
Javascript :: hook use effect with hooks 
Javascript :: react-native-image-picker npm 
Javascript :: exchange value between 2 items in array javascript 
Javascript :: why sort is not working in javascript 
Javascript :: install react hotjar 
Javascript :: chart js more data than labels 
Javascript :: loading page for all ajax call in jquery 3.3.1 
Javascript :: event.target.name in setstate 
Javascript :: asking questions javascript in console 
ADD CONTENT
Topic
Content
Source link
Name
2+6 =