DEV Community

swetha palani
swetha palani

Posted on

USESTATE IN REACT

  1. What is useState?

useState is a Hook in React, It allows functional components to have state (something only class components could do earlier with this.state).

SYNTAX:

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

Enter fullscreen mode Exit fullscreen mode
  • state → current value of the state.

  • setState → function to update the state.

  • initialValue → the value you want the state to start with.

Alright! Let’s make React Hook super clear, especially from an interview perspective.

1. What is a React Hook?

  • Hooks are special functions in React that let you “hook into” React features like state and lifecycle methods in functional components.
  • They were introduced in React 16.8 to avoid using class components for stateful logic.

Key idea: Hooks allow functional components to have state, side effects, and more without writing a class.

2. Common React Hooks

  1. useState → for state management
  2. useEffect → for side effects like API calls, timers
  3. useContext → for consuming context
  4. useReducer → for complex state management
  5. useRef → to access DOM elements or persist values

3. Why Hooks? (Advantages)

  • No need for class components → simpler, cleaner code.
  • Reuse stateful logic across components (custom hooks).
  • Better separation of concerns in components.
  • Avoids confusion with this keyword in classes.

4. Where to use Hooks?

  • Only inside functional components or custom hooks.
  • Not in loops, conditions, or nested functions → must be top-level.

5. How to use a Hook?

Example with useState:

import { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)