DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What are Hooks in React?

React Hooks are special functions that let us use React features in functional components.

For Example:

  • Store and update data.
  • Handle side effects.
  • Access other React features. Common React Hooks are useState, useEffect, useContext, and useRef.
  1. useState Hook:

useState is used to store and update a value.

Example:
Counter app.
import { useState } from "react";

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

return (


Count: {count}


setCount(count + 1)}>
Click Me


);
}

export default App;

Try the counter
0
− Decrease+ IncreaseReset

Explanation:

  • useState(0) — initializes the count to 0.
  • count — stores the current value.
  • setCount — updates the value.
  • onClick — runs when the button is clicked.

2.Common React Hooks:

Hook Purpose
useState Store and update data
useEffect Perform side effects, such as fetching data
useContext Access shared data
useRef Keep a reference to a value or DOM element
useMemo Cache a calculated result
useCallback Cache a function definition

  1. useEffect example:

useEffect runs an effect after React renders, according to its dependency array.
import { useEffect } from "react";

function App() {
useEffect(() => {
console.log("Component mounted!");
}, []);

return

Hello React!

;
}

export default App;

Here, [] means the effect runs after the component's initial mount.

Top comments (0)