Last active
January 10, 2019 22:42
-
-
Save alex-cory/fa424cd81e2b9cf8f9765235deb0f24c to your computer and use it in GitHub Desktop.
Reusable React Hooks
This file contains hidden or 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 { useState, useEffect } from 'react' | |
/** | |
* Examples of Reusable Custom Hooks | |
* - useLodash https://github.com/chantastic/use-lodash | |
* - useEvents https://github.com/sandiiarov/use-events | |
* - list of hooks https://github.com/streamich/react-use | |
* - awesome hooks https://github.com/rehooks/awesome-react-hooks | |
*/ | |
export const useToggle = (initialState = false) => { | |
const [state, setState] = useState(initialState); | |
const toggle = () => setState(state => !state); | |
return [state, toggle]; | |
} | |
export const useFetch = async ({ url, defaultData = null }) => { | |
const [data, setData] = useState(defaultData) | |
const [loading, setLoading] = useState(true) | |
const [error, setError] = useState(null) | |
useEffect(() => { | |
try { | |
const res = await fetch(url) | |
const json = await res.json() | |
setData(json) | |
setLoading(false) | |
} catch (err) { | |
setError(err) | |
setLoading(false) | |
} | |
}, []) | |
return [data, loading, error] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment