xxxxxxxxxx
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];
}
xxxxxxxxxx
//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;
xxxxxxxxxx
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;
xxxxxxxxxx
//Go to https://www.30secondsofcode.org/react/ for most commonly
//used custom hooks and components
xxxxxxxxxx
//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
xxxxxxxxxx
import { useState, useEffect } from 'react'
// Custom hook for fetching data
function useFetch(url) {
const [data, setData] = useState(null) // State for data
const [loading, setLoading] = useState(true) // State for loading
const [error, setError] = useState(null) // State for error handling
useEffect(() => {
const fetchData = async () => {
setLoading(true)
setError(null)
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`An error occurred: ${response.statusText}`)
}
const jsonData = await response.json()
setData(jsonData)
} catch (error) {
setError(error.message)
} finally {
setLoading(false)
}
}
fetchData()
}, [url]) // Dependency array with url
return { data, loading, error }
}
xxxxxxxxxx
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;
xxxxxxxxxx
//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 />);
xxxxxxxxxx
// utils/useCopyToClipboard.js
import React from "react";
import copy from "copy-to-clipboard";
export default function useCopyToClipboard() {}