DEV Community

Discussion on: Simplify controlled components with React hooks

Collapse
 
evanlk profile image
Evan Kennedy • Edited

I'd also like to point out that you could also add additional functionality such as 'setDefaults', or 'clearValues' too.

import { useState } from 'react'

export const useInputChange = (defaultValues) => {
  const [input, setInput] = useState({...defaultValues})

  const handleInputChange = (e) => setInput({
    ...input,
    [e.currentTarget.name]: e.currentTarget.value
  })

  const setDefaults = () => {
     setInput({...defaultValues});
  }

  const clearValues = () => {
    setInput({});
  }

  return [input, handleInputChange, clearValues, setDefaults]
}