Skip to content

Instantly share code, notes, and snippets.

@joshuat
Created June 9, 2020 22:50
Show Gist options
  • Save joshuat/09c5c2b047521953a7026a5bb1e12832 to your computer and use it in GitHub Desktop.
Save joshuat/09c5c2b047521953a7026a5bb1e12832 to your computer and use it in GitHub Desktop.
Context provider/hook for easy form management
import React, { createContext, useContext, useState } from 'react'
const FormContext = createContext()
export const useForm = () => {
const context = useContext(FormContext)
if (context) return context
const [formData, setFormData] = useState({})
const setField = (val, key) => {
setFormData(prev => ({
...prev,
[key]: val,
}))
}
return {
formData,
setFormData,
setField,
}
}
export const FormProvider = ({ children }) => {
const formContextParams = useForm()
return (
<FormContext.Provider value={formContextParams}>
{children}
</FormContext.Provider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment