
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Custom Hooks in ReactJS
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.
Advertisements