Skip to content

Instantly share code, notes, and snippets.

@alex-cory
Last active January 10, 2019 22:42
Show Gist options
  • Save alex-cory/fa424cd81e2b9cf8f9765235deb0f24c to your computer and use it in GitHub Desktop.
Save alex-cory/fa424cd81e2b9cf8f9765235deb0f24c to your computer and use it in GitHub Desktop.
Reusable React Hooks
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