Hook in React

In React, a “hook” is a special function that allows you to use state and other React features in functional components. Before the introduction of hooks in React 16.8, state and other features were only available in class components. Hooks provide a way to use stateful logic in functional components, making them more powerful and flexible.

There are several built-in hooks in React, and you can also create your own custom hooks. Here are some of the commonly used built-in hooks:

  1. useState:
  • Allows you to add state to functional components.
  • Example:
   import React, { useState } from 'react';

   function Counter() {
     const [count, setCount] = useState(0);

     return (
       <div>
         <p>Count: {count}</p>
         <button onClick={() => setCount(count + 1)}>Increment</button>
       </div>
     );
   }
  1. useEffect:
  • Performs side effects in your components, such as data fetching, subscriptions, or manually changing the DOM.
  • Example:
   import React, { useState, useEffect } from 'react';

   function ExampleComponent() {
     const [data, setData] = useState(null);

     useEffect(() => {
       // Perform data fetching or other side effects here
       fetchData().then((result) => setData(result));
     }, []); // Empty dependency array means this effect runs once after initial render

     return <div>{data}</div>;
   }
  1. useContext:
  • Allows you to subscribe to React context without introducing nesting.
  • Example:
   import React, { useContext } from 'react';
   import MyContext from './MyContext';

   function MyComponent() {
     const contextValue = useContext(MyContext);

     return <p>{contextValue}</p>;
   }

These are just a few examples, and React has several other hooks like useReducer, useCallback, useMemo, and more. Custom hooks are functions that use these built-in hooks to encapsulate and reuse stateful logic across components.

Remember to follow the naming convention for hooks, which is to start the function name with “use” when defining custom hooks. This helps React identify them as hooks and ensures that the rules of hooks are followed.

In React Hook is a special function that lets you “hook into” React features

Example to import Hook in React

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

useState Hook

useState is a Hook that lets you add React state to function components

Leave a Comment