Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 519

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T11:38:07+00:00 2024-11-25T11:38:07+00:00

Custom Hook – ReactJS

  • 62k

Hello πŸ‘‹, Hope you're doing well.
Before diving into the custom hook, let's revise some points about Hooks in React.

Hooks

  1. useState
  2. useEffect
  3. useContext
  4. useRef
  5. useMemo

and many more…

All of the above mentioned are in-built hooks in React. Most of us have used these hooks many times while working with functional components.

What are Hooks?

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

In simple words, Hooks are in-built functions which help React developers in managing state & lifecycle methods in a more clean & efficient way.

Rules of Hooks

  1. Don’t call hooks inside loops, conditions, or nested functions.
  2. Only call hooks from React functions.

You can read more about hooks from official docs – Hooks

All these in-built hooks are cool but what about creating our own custom hooks,
Is it possible?😯

YES!πŸ”₯

Let's create our own custom hook.
And we'll take the help of our legendary example – Counter App.

  1. Create a CounterOne.js file & write logic for increment, decrement & reset using in-built hook – useState.
import React, {useState} from 'react'  const CounterOne = () => {    const [count, setCount] = useState(0);    const increment = () => {     setCount(count => count + 1)   }    const decrement = () => {     setCount(count => count - 1)   }    const reset = () => {     setCount(0)   }    return(     <div>       <h1>Count: {count}</h1>       <button onClick={increment}>Increment</button>       <button onClick={decrement}>Decrement</button>       <button onClick={reset}>Reset</button>     </div>   ) }  export default CounterOne 
Enter fullscreen mode Exit fullscreen mode

  1. Import CounterOne.js in App.js
import CounterOne from "./CounterOne"; import "./styles.css";  export default function App() {   return (     <div className="App">       <CounterOne />     </div>   ); } 
Enter fullscreen mode Exit fullscreen mode

Now we can increment, decrement & reset the counter.

counter app

What if we want one more counter – easy no?
We'll copy the code of CounterOne.js in CounterTwo.js & Import it in App.js.

import React, {useState} from 'react'  const CounterTwo = () => {    const [count, setCount] = useState(0);    const increment = () => {     setCount(count => count + 1)   }    const decrement = () => {     setCount(count => count - 1)   }    const reset = () => {     setCount(0)   }    return(     <div>       <h1>Count: {count}</h1>       <button onClick={increment}>Increment</button>       <button onClick={decrement}>Decrement</button>       <button onClick={reset}>Reset</button>     </div>   ) }  export default CounterTwo 
Enter fullscreen mode Exit fullscreen mode

Here we go. we have now two counters on the view.

Two counter app

But doing copy/paste of whole logic isn't a good practice. We should avoid repeating ourselves.

Now we'll take advantage of creating a custom hook & extract our logic in a separate file.

  1. Create a useCounter.js file.

we must prefix the custom hook's name with use.

  1. Now we'll extract the logic part with in-built hook – useState. and yes, we can use in-built hooks in our custom hook.
import { useState } from "react";  const useCounter = () => {   const [count, setCount] = useState(0);    const increment = () => {     setCount((count) => count + 1);   };    const decrement = () => {     setCount((count) => count - 1);   };    const reset = () => {     setCount(0);   };    return [count, increment, decrement, reset]; };  export default useCounter; 
Enter fullscreen mode Exit fullscreen mode

At last, we return all the necessary variables & functions – count, increment, decrement, reset in an array.

That's it, we just made our own custom hook. πŸŽ‰

Now we can use useCounter hook in our functional components.

We just need to import this hook & use it using array destructuring.

const [count, increment, decrement, reset] = useCounter(); 
Enter fullscreen mode Exit fullscreen mode

CounterOne.js

import React from "react"; import useCounter from "./useCounter";  const CounterOne = () => {   const [count, increment, decrement, reset] = useCounter();    return (     <div>       <h1>Count: {count}</h1>       <button onClick={increment}>Increment</button>       <button onClick={decrement}>Decrement</button>       <button onClick={reset}>Reset</button>     </div>   ); };  export default CounterOne; 
Enter fullscreen mode Exit fullscreen mode

CounterTwo.js

import React from "react"; import useCounter from "./useCounter";  const CounterTwo = () => {   const [count, increment, decrement, reset] = useCounter();   return (     <div>       <h1>Count: {count}</h1>       <button onClick={increment}>Increment</button>       <button onClick={decrement}>Decrement</button>       <button onClick={reset}>Reset</button>     </div>   ); };  export default CounterTwo; 
Enter fullscreen mode Exit fullscreen mode

Here's the code sandbox link – useCounter

Conclusion

Hope after reading this blog, now you know –

  1. how to create a custom hook.
  2. how to use it in a functional component.

If you find this blog as helpful, don't forget to share it.

Thank you πŸ™‚
Connect with me on – Twitter Instagram

reacttutorialwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.