Skip to content

Instantly share code, notes, and snippets.

@GraySmith00
Last active May 12, 2020 11:55
Show Gist options
  • Save GraySmith00/0f6f0cfb7cbb6166c1293033aa961aa6 to your computer and use it in GitHub Desktop.
Save GraySmith00/0f6f0cfb7cbb6166c1293033aa961aa6 to your computer and use it in GitHub Desktop.

Custom React Hooks

useForm

import {useState} from 'react';

export const useForm = () => {
  const [values, setValues] = useState(initialValues);
  
  return [
    values, 
    e => {
      setValues({
        ...values,
        [e.target.name]: e.target.value
      });
    }
}

useFetch

import {useEffect} from 'react';

export const useFetch = (url) => {
  const [state, setState] = useState({ data: null, loading: true })

  useEffect(() => {
    setState(stat => ({ data: state.data, loading: true }));
  
    const fetchData = async () => {
      const response = await fetch(url);
      const data = response.json()
      setState({ data, loading: false });
    }
    
    fetchData()
  }, [url, setState]);
  
  return state
  
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment