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 :: js array append 
Javascript :: react native get screen height and width 
Javascript :: moment js get last week start and end date 
Javascript :: vs code ouput stack 
Javascript :: color switcher 
Javascript :: how to add suffix to a string in javascript 
Javascript :: javascript prefill form 
Javascript :: port y build - vite.config.js 
Javascript :: javascript DOM SELECT 
Javascript :: js add obj prop dynamically 
Javascript :: Convert to String Explicitly 
Javascript :: JavaScript Constructor Function Parameters 
Javascript :: javascript Rename in the module 
Javascript :: javascript Nested Destructuring Assignment 
Javascript :: Create JavaScript Generators 
Javascript :: K= K*7,K=10+K; console.log( K= K/2); 
Javascript :: simple counter with react hook 
Javascript :: convert string to slug javascript 
Javascript :: largest element in nested array 
Javascript :: calculate age from date of birth javascript 
Javascript :: phaser wrap in rectangle 
Javascript :: accessing-nested-javascript-objects-and-arrays-by-string-path 
Javascript :: rotate matrix 90 degrees javascript 
Javascript :: nodejs stream pipeline 
Javascript :: HSETNX in redis 
Javascript :: javascript setinterval run immediately 
Javascript :: regex capture group example 
Javascript :: what is slot in vue.js 
Javascript :: javascript no decimal places 
Javascript :: react sass 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =