Custom Hooks in ReactJS

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to learn how to define custom hooks in ReactJS.

All the rules and usage guidelines are the same as that of the predefined ReactJS hooks like −

  • Call Hooks at the Top Level

  • Call Hooks from React Functions only

Example

In this example, we will build an input validator application that will display some text based on the user-defined conditions in the custom hook.

App.jsx

import React from 'react';
import useForm from './CustomHook';

const App = () => {
   const input = useForm();
   return (
      <div>
      <input onChange={input.onChange} value={input.value} />
      {input.valid ? 'Welcome to TutorialsPoint' : 'Try again'}
      </div>
   );
};
export default App;

CustomHook.jsx

import React, { useState } from 'react';

const useForm = () => {
   const [val, setVal] = useState('');
   const [valid, setValid] = useState(false);

   const inputHandler = (e) => {
      setVal(e.target.value);
      e.target.value === 'TutorialsPoint' ? setValid(true) : setValid(false);
   };
   return { value: val, onChange: inputHandler, valid };
};

export default useForm;

In the above example, when the user types in the input field, then the custom hook is called which decides whether the text is valid or not based on certain conditions.

Output

This will produce the following result.

raja
Published on 18-Mar-2021 10:35:24

Advertisements