React Hooks

Introduction of React Hooks

React Hooks are fully opt-in which implies that editing existing code is unnecessary, they do not contain any breaking changes, and they’re obtainable to be used with the discharge of React 16.8. Some curious developers are creating use of the Hooks API even before it had been discharged formally, but back then it was not stable and was only an experimental feature. Now it’s stable and suggested for React developers to use.

Basics of React Hooks:

  • useEffect()
  • useState()
Change The Message 3 Seconds After The Component Is Mounted Using useEffect()

React useEffect() function can be executed in 3 different React component life cycles, that are:

  1. componentDidMount
  2. componentDidUpdate
  3. componentWillUnmount

Let’s understand the useEffect() hook by taking the belowexample. So let’s say I want to change the message 3 seconds after the component is mounted.

import React, { useState, useEffect } from "react";
const App= () => {
  const [count, setCount] = useState(0);
  useEffect(() => {
    console.log("Where are you.?");
    setTimeout(() => {
      console.log("I'M Hear...!");
    }, 3000);
  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default App;

Output 1:

In this example we have used the useEffect() hook to trigger the “Where are you.?” fIrst

React Hooks
Output 2:

“I’M Hear…!” will be trigger after 3 seconds because of using setTimeout()

React Hooks

Token Generator using useState()

The following Concept we are going to generate the tokens for the various inputs.

Step 1:

  • Create a React Application Using – npx create-react-app my-app commend .
  • Install the Packages Using – npm install command.
  • Start the Program Using – npm start command. 
  • Install the Axios Package For API Integration Using – npm i axios commend.
  • Install useState Packages Using – npm i usestate commend.

Step 2:

Updating the state variable is as simple as invoking the updater function returned by the useState invocation:

const [textInput, setTextInput] = useState(‘ ‘);
const [textvalue, settextvalue] = useState(‘ ‘);

Step 3:

  • In the handleSubmit function, we fetch the TextField and pass the data to API params.
  • When type the text in text box get the value from  const [textInput, setTextInput] = useState(‘ ‘); 
  • Then give the params as a textInput.
  • Then get the token from  const [textvalue, settextvalue] = useState(‘ ‘); 
Example Token Generator using Hooks :
import './App.css';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import axios from 'axios';
import { useState } from 'react';
import React, { useRef } from 'react'
function App() {
  const [textInput, setTextInput] = useState('');
  const [textvalue, settextvalue] = useState('');
  function refreshPage() {
    window.location.reload(false);
  }
    const handleTextInputChange = event => {
        setTextInput(event.target.value);
    };
  function handleSubmit(e) {
    axios.post('http://localhost:4001/api/user/Token/'+ textInput).then((data) => {
      settextvalue(data.data.token);
    })
    .catch((err) => {
        alert("Please Type Somthing");
        <form>
            <input type="button" value="Click Me" onclick={window.location.href = "/"} />
        </form>
    });
}
  return (
        <Box
      sx={{
        '& > :not(style)': { m: 1, width: '25ch' },
      }}
      noValidate
      autoComplete="off"
    >
      <h1>Token Generator</h1>
      <div><TextField id="outlined-basic" className='textfield' label="Type Hear" value= {textInput} onChange= {handleTextInputChange}/></div>
      <div><Button variant="contained"  onClick={handleSubmit}>Click</Button></div>
      <div><TextField
          className='textfield'
           id="outlined-multiline-static"
          label="Token"
          multiline
          rows={6}
          defaultValue="Default Value"
          variant="filled"  
          value= {textvalue}
        /></div>
        <div><Button variant="contained" onClick={refreshPage}>Refresh</Button></div>
    </Box>
  );
}

export default App;

Output:

Function: 

In this above example axios to use for API Call when trigger the Textinput it goes to the useState(‘ ‘) then gets the input text on state next it will move trigger api and it gives output Token.

Conclusion:

React Hooks: As we tend to mentioned earlier, Hooks is a unit of specialized JavaScript functions that aim to resolve the problems you will experience once operating with React category elements. they permit useful elements to use React options solely accessible with React categories by supplying you with direct and versatile access to those options.