0
0
ReactConceptBeginner · 3 min read

What is use hook in React: Simple Explanation and Example

In React, a hook is a special function that lets you use React features like state and lifecycle inside functional components. The most common hook is useState, which helps you add and manage state without writing a class.
⚙️

How It Works

Think of a hook as a helper that lets your React component remember things or react to changes, even though it is just a simple function. Normally, only class components could hold state or run code when the component appears or updates. Hooks let functional components do the same in a clean and easy way.

Imagine you have a notebook (the component) and hooks are like sticky notes you attach to it. These sticky notes keep track of important details (like a counter number) or tell the notebook to do something when it opens or changes. This way, your component stays simple but powerful.

💻

Example

This example shows how to use the useState hook to create a button that counts how many times you click it.

jsx
import React, { useState } from 'react';

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

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

export default ClickCounter;
Output
You clicked 0 times (initially). Each click on the button increases the count number shown.
🎯

When to Use

Use hooks whenever you want to add state, side effects, or other React features inside functional components. They are perfect for:

  • Keeping track of user input or clicks
  • Fetching data from a server when a component loads
  • Running code when something changes, like a timer or animation
  • Sharing logic between components without repeating code

Hooks make your code simpler and easier to understand compared to older class-based components.

Key Points

  • Hooks let functional components use React features like state and lifecycle.
  • useState is the most common hook for managing state.
  • Hooks must be called at the top level of a component, not inside loops or conditions.
  • They help keep components simple and reusable.

Key Takeaways

Hooks enable state and other React features in functional components.
useState is used to add and update state values.
Hooks simplify component logic and improve code reuse.
Always call hooks at the top level of your component function.