Last active
September 15, 2022 05:22
-
-
Save sidsbrmnn/951c1f5b1e77f10f6c22dbd20e175a2d to your computer and use it in GitHub Desktop.
React hooks in Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import queryString from 'query-string'; | |
import { useMemo, useState } from 'react'; | |
import { useHistory, useLocation, useParams, useRouteMatch } from 'react-router-dom'; | |
export function useLocalStorage<T>(key: string, initialValue: T) { | |
const [storedValue, setStoredValue] = useState<T>(() => { | |
try { | |
const item = window.localStorage.getItem(key); | |
return item ? JSON.parse(item) : initialValue; | |
} catch(error) { | |
console.log(error); | |
return initialValue; | |
} | |
}); | |
const setValue = (value: T | (val: T) => T) => { | |
try { | |
const valueToStore = value instanceof Function ? value(storedValue) : value; | |
setStoredValue(valueToStore); | |
window.localStorage.setItem(key, JSON.stringify(valueToStore)); | |
} catch(error) { | |
console.log(error); | |
} | |
}; | |
return [storedValue, setValue]; | |
} | |
export function useRouter() { | |
const history = useHistory(); | |
const location = useLocation(); | |
const params = useParams(); | |
const match = useRouteMatch(); | |
return useMemo(() => { | |
return { | |
push: history.push, | |
replace: history.replace, | |
pathname: location.pathname, | |
query: { | |
...queryString.parse(location.search), | |
...params, | |
}, | |
history, | |
location, | |
match, | |
}; | |
}, [history, location, params, match]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment