Custom Hooks - Web dev simplified
AKSH DESAI
Posted on January 4, 2023
Part 1
Folder Structure
App.js Code
import useFetch from "./useFetch";
const App = () => {
// const [data, setData] = useState(null);
// useEffect(() => {
// fetch("https://aksh-crud.azurewebsites.net/api/v1")
// .then((res) => res.json())
// .then((data) => setData(data));
// }, []);
const data = useFetch("https://aksh-crud.azurewebsites.net/api/v1");
console.log('parent', data);
return (
<>
{!data ? <h1> Loading Data </h1> :
data.map((item) => {
return <h1 key={item._id}>{item.title} - {item.desc} <hr /></h1> ;
})}
</>
);
};
export default App;
useFetch.js Code
import { useState, useEffect } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
console.log('useEffect children', data);
fetch(url)
.then((res) => res.json())
.then((data) => {
setData(data)
});
// eslint-disable-next-line
}, [url]);
return data;
};
export default useFetch;
Output
Part 2
Folder Structure
App.js Code
import useLocalStorage from './useLocalStorage'
import useUpdateLogger from './useUpdateLogger';
export default function App() {
const [name, setName] = useLocalStorage("name", '');
const [sname, setSname] = useLocalStorage("sname", '');
useUpdateLogger(name)
console.log('app component');
return (
<>
<input type="text" value={name} onChange={e => setName(e.target.value)} />
{name}
<input type="text" value={sname} onChange={e => setSname(e.target.value)} />
{sname}
</>
)
}
useLocalStorage.js Code
import { useState, useEffect } from 'react'
function getSavedValue(key, initialValue) {
console.log('inside getSavedValue');
const savedValue = localStorage.getItem(key) === '' ? '' : JSON.parse(localStorage.getItem(key));
if (savedValue) return savedValue;
if (initialValue instanceof Function) return initialValue();
return initialValue
}
export default function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
return getSavedValue(key, initialValue);
});
useEffect(() => {
console.log('children useEffect');
localStorage.setItem(key, JSON.stringify(value));
console.log(localStorage.setItem(key, JSON.stringify(value)));
}, [value]);
console.log('children component');
return [value, setValue];
}
useUpdateLogger.js Code
import { useEffect } from 'react'
const useUpdateLogger = (value) => {
useEffect(() => {
console.log('useUpdateLogger', value);
}, [value])
return (
<div>
updatelogger component
</div>
)
}
export default useUpdateLogger
💖 💪 🙅 🚩
AKSH DESAI
Posted on January 4, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
watercooler Why does a reboot make your PC run SO much faster than running all the cleaning tools you can possibly imagine?
November 30, 2024