create custom hooks react

How to Create Custom Hooks React Example

What are hooks?

React hooks with simple words are tasks. When you insert them into your object or inside another hook, it allows you to use React internals and React lifecycle components with traditional hooks such as State and Effect.

I do not plan to make a deep dive about hooks, but you can check out a quick introduction with an example State and an introduction from the React group.

Why are Create Custom Hooks React ?

The great thing about creating custom hooks is it allows you to have an unobtrusive view of your objects making it easy to reuse a lot of things in your app.

Read Also :  React Bootstrap Card Example

For example, if you wanted to create a simple counter where you use the React status to manage the current figure. Instead of having the same State State hook for each object file, you can create that logic once in the useCustomCount hook, making it easy to care for, expand, and squash squares when they appear.

Read Also :  How to Use Strict Mode in React

Create Custom Hooks React Example

Index.js

import React from 'react';
import ReactDOM from 'react-dom'
import useCustomCount from './Custom'

function Example() {
  const data = useCustomCount();
  return (
    <div>
    <p>You clicked {data.count} times</p>
    <button onClick={data.handelCount}>
      Click me
    </button>
    </div>
  );
}

ReactDOM.render(<Example />,document.getElementById("root"));

Custom.js

import  { useState } from 'react'

function useCustomCount(){
    const [count, setCount] = useState(0);
    const handelCount = () =>{
        setCount(count + 1);
    }
    return{
        count,
        handelCount
    }
}

export default useCustomCount;