Skip to content

Instantly share code, notes, and snippets.

@srph
Last active May 7, 2019 06:55
Show Gist options
  • Save srph/2053cf063d2e0cda850055f27f0db424 to your computer and use it in GitHub Desktop.
Save srph/2053cf063d2e0cda850055f27f0db424 to your computer and use it in GitHub Desktop.
React Hook: useFormState
const form = useFormState({ 
  email: '',
  password: ''
})

// returns form.setEmail, form.email, form.setPassword, and form.password
<input value={form.email} onChange={form.setEmail} />

<input value={form.password} onChange={form.setPassword} />
import { useState, useMemo } from 'react'
/**
* @source https://gist.github.com/srph/2053cf063d2e0cda850055f27f0db424
*/
function useFormState(initial) {
const [state, setState] = useState(initial)
return useMemo(() => {
let out = {}
Object.keys(state).forEach(key => {
out[key] = state[key]
out[`set${ucFirst(key)}`] = (evt) => setState({
...state,
[key]: evt.target.value
})
})
return out
}, [initial])
}
export default useFormState
function ucFirst(str) {
return str.charAt(0).toUpperCase() + str.substr(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment