How to use the React hooks

How to use the React hooks

In this post we will give you information about How to use the React hooks. Hear we will give you detail about How to use the React hooksAnd how to use it also give you demo for it if it is necessary.

we are going to learn about how to use the hooks in react with the help of examples.

React hooks helps us to implement the stateful functional components.

View demo ⚛️

Let’s play with react hooks.

Run the following commands in your terminal to create a new react app.

npx create-react-app react-hookscd react-hooksnpm start

Now, create a two new components called signin.js and counter.js.

signin.js
import React from 'react';function Signin(props) {    return <button        onClick={props.isSignin ? props.Signout : props.Signin} >        {props.isSignin ? "Signout" : "Sign in"}</button>}export default Signin;
counter.js
import React from 'react';export default (props) => {    return (        <div>        <h1> {props.value}</h1>        <button onClick={props.Increment} >Increment</button>        <button onClick={props.Decrement} >Decrement</button>        </div>    )}

Let’s write some hooks.

What is a hook?

A hook is a function which helps us to use the react features

For example in the below code useState hook is used to add the state in functional components.

useState hook

App.js
import React, { useState } from 'react';import './App.css';import Signin from './signin';import Counter from './counter';function App(props) {   console.log(useState(0));  return (    <div className="App">      <header className="App-header">      </header>    </div>  );}export default App;

In the above code, first we imported the two components which we created above and we invoked the useState() hook method by passing an intial state 0.

useState() hook returns the array with two elements which are the current state and the function which is used to update the state.

Let’s use that two elements by using array destructuring.

App.js
import React, { useState } from 'react';import './App.css';import Signin from './signin';import Counter from './counter';function App(props) {  <span>const [value, Setvalue] = useState(0);  function Incvalue() {    return Setvalue(value + 1)  }  function Decvalue() {    return Setvalue(value - 1)  }  return (    &lt;div className="App"&gt;      &lt;header className="App-header"&gt;        &lt;Counter value={value} Increment={Incvalue} Decrement={Decvalue} /&gt;      &lt;/header&gt;    &lt;/div&gt;  );}export default App;

that’s it we successfully created our first stateful functional component by using hooks.

Custom React hooks.

custom react hooks are just javascript functions which start with word “use”.

Let’s create our own react custom hook.

status.js
import { useState } from 'react';function useSigninStatus(status) {    const [isSignin, setSignin] = useState(status);    function Signin() {        setSignin(true)    }    function Signout() {        setSignin(false)    }    return {        isSignin,        Signin,        Signout,    }}export default useSigninStatus;

How to use custom react hooks?

We can use custom react hooks by just importing it, so that we are now importing our useSigninStatus hook from the status.js file.

App.js
import React, { useState, useEffect } from 'react';import './App.css';import Signin from './signin';import Counter from './counter';<span>import useSigninStatus from './status';function App(props) {  const [value, Setvalue] = useState(0);  let status = useSigninStatus(false);  function Incvalue() {    return Setvalue(value + 1)  }  function Decvalue() {    return Setvalue(value - 1)  }  return (    &lt;div className="App"&gt;      &lt;header className="App-header"&gt;        &lt;Signin {...status} /&gt;        &lt;Counter isSignin={status.isSignin} value={value}          Increment={Incvalue} Decrement={Decvalue} /&gt;      &lt;/header&gt;    &lt;/div&gt;  );}export default App;

useReducer hook

By using reducer hook we can create and dispatch the actions, it means we can use the redux by using useReducer hook.

Let’s rewrite our code by using useReducer hook.

reducer.js
function reducer(state, action) {    switch (action.type) {        case "Increment":            return {                ...state,                value: state.value + 1            };        case "Decrement":            return {                ...state,                value: state.value - 1            }        case "Resetcounter":            return {                ...state,                value: 0,            }        case "Signin":            return {                ...state,                isSignin: true            };        case "Signout":            return {                ...state,                isSignin: false            }        default:            return state    }}export { reducer };

Let’s import the reducer function inside the App component.

App.js
import React, { useReducer, useEffect } from "react";import "./App.css";import { reducer } from "./reducer";import Auth from "./signin";import Counter from "./counter";function App(props) {  let [state, dispatch] = useReducer(reducer, { value: 0, isSignin: false });  return (    &lt;div className="App"&gt;      &lt;header className="App-header"&gt;        &lt;Auth          isSignin={state.isSignin}          Signin={() =&gt; {            dispatch({ type: "Signin" });          }}          Signout={() =&gt; {            dispatch({ type: "Signout" });          }}        /&gt;        &lt;Counter          isSignin={state.isSignin}          value={state.value}          Increment={() =&gt; {            dispatch({ type: "Increment" });          }}          Decrement={() =&gt; {            dispatch({ type: "Decrement" });          }}        /&gt;      &lt;/header&gt;    &lt;/div&gt;  );}export default App;

In the above, first we imported the reducer from the reducer.js file and passed it to the userReducer() hook.

useReducer: The useReducer hook takes the two arguments the first argument is reducer function the second argument is initial state.

The useReducer hook returns the current state and dispatch method, so that we can dispatch the actions.

useEffect hook

The useEffect hook helps to use the lifecycle methods such as componentDidMount, componentDidUpdate and componentWillUnmount.

The useEffect hook runs on the first render and also run every time when a component updates.

 useEffect(() =&gt; {        if (!state.isSignin) {            dispatch({ type: "Resetcounter" })        }    })

We are using the useEffect hook to reset the counter value to 0.


Hope this code and post will helped you for implement How to use the React hooks. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US