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;
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;
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];
}
react hooks, react custom hooks
//Go to https://www.30secondsofcode.org/react/ for most commonly
//used custom hooks and components
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;
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
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 />);