added 2 custom hooks
This commit is contained in:
20
client/src/hooks/useLocalStorage.js
Normal file
20
client/src/hooks/useLocalStorage.js
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import {useState, useEffect} from 'react'
|
||||||
|
|
||||||
|
/* How to use this hook:
|
||||||
|
import useLocalStorage from './hooks/useLocalStorage';
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const [example, setExample] = useLocalStorage('example_key', {example: 'anything as default'});
|
||||||
|
|
||||||
|
return ();
|
||||||
|
}; */
|
||||||
|
|
||||||
|
export default function useLocalStorage(key = '', defaultValue = null) {
|
||||||
|
const [value, setValue] = useState(JSON.parse(localStorage.getItem(key)) || defaultValue)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (value != null) localStorage.setItem(key, JSON.stringify(value))
|
||||||
|
}, [key, value])
|
||||||
|
|
||||||
|
return [value, setValue]
|
||||||
|
}
|
||||||
24
client/src/hooks/useMediaQuery.js
Normal file
24
client/src/hooks/useMediaQuery.js
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import {useState, useEffect} from 'react'
|
||||||
|
|
||||||
|
/* How to use this hook:
|
||||||
|
import useMediaQuery from './hooks/useMediaQuery';
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||||
|
|
||||||
|
return ();
|
||||||
|
}; */
|
||||||
|
|
||||||
|
export default function useMediaQuery(query = '(max-width: 768px)') {
|
||||||
|
const [matches, setMatches] = useState(window.matchMedia(query).matches)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const media = window.matchMedia(query)
|
||||||
|
const listener = () => setMatches(media.matches)
|
||||||
|
|
||||||
|
media.addListener(listener)
|
||||||
|
return () => media.removeListener(listener)
|
||||||
|
}, [query])
|
||||||
|
|
||||||
|
return matches
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user