Simple React hook to handle input
Rafi

Rafi @rafi993

About: I'm a developer who works mostly with Javascript.

Joined:
Feb 19, 2018

Simple React hook to handle input

Publish Date: Mar 31 '20
18 5

When building in react often you have to deal with different inputs like text, number, date... and each time it is kind of annoying to write onChange handlers with same boiler plate code to handle the local state. I wrote a really simple hook to avoid that boiler plate

import { useState, useCallback } from 'react';

const useInput = initialValue => {
  const [value, setValue] = useState(initialValue);

  const handleChange = useCallback(
    event => {
      setValue(event.target.value);
    },
    [setValue]
  );

  return { value, handleChange, setValue };
};

export default useInput;

and you can use this as follows

import useInput from './useInput';

const App = () => {
  const { value, handleChange } = useInput('');

  return <input value={value} onChange={handleChange} />;
};

export default App;

Comments 5 total

  • Narender Saini
    Narender SainiApr 1, 2020

    I think you need to pass value as dependency to useCallback instead of setValue ?

    • Rafi
      RafiApr 1, 2020

      The value used inside handleChange is event.target.value different from outside value.

      • Narender Saini
        Narender SainiApr 1, 2020

        I mean instead of
        const handleChange = useCallback(
        event => {
        setValue(event.target.value);
        },
        [setValue]
        );

        this you can write

        const handleChange = useCallback(
        event => {
        setValue(event.target.value);
        },
        [value]
        );

        • Rafi
          RafiApr 1, 2020

          Hmm. I don't think value needs to be passed as dependency since it not being used but I need to check.

          • Thomas Werner
            Thomas WernerApr 1, 2020

            I think your original code is correct and adding value as a dependency would be a mistake. It's not referenced inside the callback, nor should it be added as a dependency, otherwise your callback function would be re-created on every single value change, which would defy the purpose of using that callback hook there. There's no reason for your event handler to change when the input value changes.

            React's console output usually contains good information and warning messages about missing dependencies. So if value or anything else was required for your callback you would see that in your log output.

Add comment