hook for handling Inputs
custom hooks

Have you ever faced a situation where you need to render a lot of inputs and you also need to write same code multiple times for handling inputs. In this post we are going to learn about a new way to handle inputs by creating a Reusable hook for handling the inputs.

Hooks

With the introduction of Hooks in React a lot of complex logic become easy unlike never before. Hooks are the new way to manage reactive variable in functional components. If you haven’t study Hooks yet you can checkout this article.

Hook for handling Inputs

We are going to create a simple hooks which basically gonna have 3 parts

  1. It will gonna use hooks for setting input value.
  2. We gonna use useCallback or useMemo for better performance.
  3. We gonna return value and onChange object from hook.

First we gonna import required functions i.e useState and useCallback.

import { useState, useCallback } from 'react';

After that we gonna create a function useInput which gonna return an object.

export const useInput = initialValue => {
  
  return { };
};

Now we gonna use a hook value for storing the input value.

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

After that we gonna write our onChange handler which basically gonna store new values on onChange.

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

After that we simply gonna return an object which gonna have an value and a onChange function.

return { value, onChange  };

Our final component gonna look like this now.

import { useState, useCallback } from 'react';

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

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

  return { value, handleChange };
};

We can simply use our useInput hook in anywhere in our project.

import useInput from './useInput';

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

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

export default App;

I hope you have learned how to create a reusable hook for handling Inputs in React.


1 Comment

How to use Popperjs with React - Blog React · April 2, 2020 at 4:12 am

[…] Reusable hook for handling Inputs in React Categories: Reactjs Tags: popperReactjs Advanced […]

Comments are closed.