Author -  Sai gowtham

How to use the React hooks

In this tutorial, 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-hooks
cd react-hooks
npm 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.

use state react hook demo

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) {

  const [value, Setvalue] = useState(0);
  function Incvalue() {
    return Setvalue(value + 1)
  }

  function Decvalue() {
    return Setvalue(value - 1)
  }

  return (
    <div className="App">
      <header className="App-header">
        <Counter value={value} Increment={Incvalue} Decrement={Decvalue} />
      </header>
    </div>
  );

}

export default App;

react hooks counter demo

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';
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 (
    <div className="App">
      <header className="App-header">
        <Signin {...status} />
        <Counter isSignin={status.isSignin} value={value}
          Increment={Incvalue} Decrement={Decvalue} />
      </header>
    </div>
  );
}

export default App;

react hooks authorization demo

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 (
    <div className="App">
      <header className="App-header">
        <Auth
          isSignin={state.isSignin}
          Signin={() => {
            dispatch({ type: "Signin" });
          }}
          Signout={() => {
            dispatch({ type: "Signout" });
          }}
        />
        <Counter
          isSignin={state.isSignin}
          value={state.value}
          Increment={() => {
            dispatch({ type: "Increment" });
          }}
          Decrement={() => {
            dispatch({ type: "Decrement" });
          }}
        />
      </header>
    </div>
  );
}

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(() => {
        if (!state.isSignin) {
            dispatch({ type: "Resetcounter" })
        }
    })

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


Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY