"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Custom Hooks

Custom Hooks

Published on 2024-11-04
Browse:120

Explain Me React Hooks

React Hooks are functions that let you use state and other React features without writing a class. Introduced in React 16.8, they enable functional components to handle logic like state management, lifecycle events, and side effects.

Custom Hooks

What is Need of Custom Hooks ?

Custom React Hooks allow you to extract and reuse logic across multiple components. They help to keep components clean and reduce duplication by encapsulating stateful logic into a function. Custom Hooks follow the same rules as built-in Hooks (e.g., they can use other Hooks like useState, useEffect, etc.).

Show Me the Code :

import React, { useState } from 'react';


// Custom Counter Hooks
const useCounter = (initialValue = 0) => {
  const [count, setCount] = useState(initialValue);

  const increment = () => setCount(value=>value   1);
  const decrement = () => setCount(value=>value - 1);
  const reset = () => setCount(initialValue);

  return { count, increment, decrement, reset };
};
export default useCounter;

import useCounter from './useCounter';

const Counter = () => {

  // Using Counter Hooks
  const { count, increment, decrement, reset } = useCounter();

  return (
    

{count}

); };

Rules for Custom Hooks

Only call hooks at the top level: Don’t call hooks inside loops, conditions, or nested functions.

Only call hooks from React functions: Hooks should be used in functional components or other custom hooks.

Release Statement This article is reproduced at: https://dev.to/vaibhav_shukla_newsletter/custom-hooks-4bf0?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3