React JS

What is Hooks in React JS

Interview Answer

Hooks are built-in React functions that allow Functional Components to use state, lifecycle methods, context, and other React features without using Class Components. Common Hooks include useState, useEffect, useRef, useMemo, and useCallback. Hooks make React code simpler, reusable, and easier to maintain.

What are Hooks in React?

Hooks are special functions introduced in React 16.8 that allow Functional Components to use React features such as state, lifecycle methods, context, and more without writing Class Components.

Before Hooks, state and lifecycle methods were only available in Class Components.


Why Hooks?

Without Hooks (Class Component):

class Counter extends React.Component {
state = {
count: 0
};

render() {
return <h1>{this.state.count}</h1>;
}
}

With Hooks (Functional Component):

import { useState } from "react";

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

return <h1>{count}</h1>;
}

Less code and easier to maintain.


Common React Hooks

1. useState()

Used to manage component state.

import { useState } from "react";

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

return (
<>
<h2>{count}</h2>

<button onClick={() => setCount(count + 1)}>
Increment
</button>
</>
);
}

Syntax

const [state, setState] = useState(initialValue);

2. useEffect()

Used for side effects such as:

  • API Calls
  • Timers
  • Event Listeners
  • Lifecycle Events

componentDidMount Equivalent

useEffect(() => {
console.log("Page Loaded");
}, []);

Runs only once after component loads.

componentDidUpdate Equivalent

useEffect(() => {
console.log("Count Changed");
}, [count]);

Runs whenever count changes.

componentWillUnmount Equivalent

useEffect(() => {
return () => {
console.log("Component Removed");
};
}, []);

3. useMemo()

Used to cache expensive calculations.

const total = useMemo(() => {
return products.reduce((sum, item) => sum + item.price, 0);
}, [products]);

Prevents recalculating on every render.


4. useCallback()

Used to cache functions.

const saveData = useCallback(() => {
console.log("Saving...");
}, []);

Useful when passing functions to child components.


5. useRef()

Stores a value without causing re-render.

Focus Input Example

import { useRef } from "react";

function Login() {
const inputRef = useRef();

const focusInput = () => {
inputRef.current.focus();
};

return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Focus</button>
</>
);
}

6. useContext()

Used to share data globally without prop drilling.

const UserContext = createContext();

const user = useContext(UserContext);

Useful for:

  • Theme
  • Authentication
  • Language Settings

7. useReducer()

Used for complex state management.

const reducer = (state, action) => {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };

default:
return state;
}
};

const [state, dispatch] = useReducer(reducer, {
count: 0
});

Rules of Hooks

✅ Correct

function User() {
const [name, setName] = useState("");
}

❌ Wrong

if (true) {
useState("");
}

Never call Hooks:

  • Inside loops
  • Inside conditions
  • Inside nested functions

Always call Hooks at the top level of the component.


Most Frequently Used Hooks in Projects

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