BC.

Full Stack Web & Mobile App Developer

React.js Interview Questions

Found 399 questions

21. What is the difference between controlled and uncontrolled components?

Feature

Controlled Component

Uncontrolled Component

Form Data Location

Stored in React state

Stored in the DOM

Value Control

React controls the input value

DOM controls the input value

Data Access

Through state variables

Through refs

Validation

Easier to validate and update

More manual handling

Recommended

Yes, for most forms

Useful for simple cases or integrations

Controlled Component

function Form() {
  const [name, setName] = React.useState("");

  return (
    <input
      value={name}
      onChange={(e) => setName(e.target.value)}
    />
  );
}

Uncontrolled Component

function Form() {
  const inputRef = React.useRef();

  const handleSubmit = () => {
    console.log(inputRef.current.value);
  };

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleSubmit}>Submit</button>
    </>
  );
}

Summary

Controlled components keep form data in React state, making them easier to manage and validate. Uncontrolled components keep data in the DOM and are accessed using refs.

22. How do forms work in React?

Forms in React are usually handled using controlled components, where form values are stored in React state and updated through event handlers. When a user types into an input, React updates the state and re-renders the UI with the latest value.

Example

function LoginForm() {
  const [email, setEmail] = React.useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(email);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />

      <button type="submit">
        Submit
      </button>
    </form>
  );
}

Common Form Events

  • onChange → Detect input changes

  • onSubmit → Handle form submission

  • onBlur → Detect when an input loses focus

  • onFocus → Detect when an input gains focus

Summary: React forms typically store input values in state and update them through event handlers, giving React full control over the form data.

23. What are synthetic events in React?

Synthetic Events are React's wrapper around native browser events. They provide a consistent event API across different browsers, so event handling works the same way everywhere.

Example

function Button() {
  const handleClick = (event) => {
    console.log(event.type); // "click"
  };

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}

Here, event is a React Synthetic Event, not the raw browser event.

Benefits

  • Cross-browser compatibility

  • Same event behavior across browsers

  • Simple and consistent API

  • Works with React's event system

Access Native Event

event.nativeEvent

Summary: Synthetic Events are React's cross-browser event objects that provide a consistent way to handle user interactions like clicks, input changes, and form submissions.

24. How does React event handling differ from native DOM events?

Feature

React Event Handling

Native DOM Events

Event Object

Synthetic Event

Native Browser Event

Event Names

CamelCase (onClick)

Lowercase (onclick)

Event Binding

Passed as JSX props

Added with addEventListener()

Cross-Browser Support

Built-in consistency

Browser differences may exist

Prevent Default

event.preventDefault()

event.preventDefault()

Event Delegation

Handled by React internally

Managed by the browser

React Example

function App() {
  const handleClick = () => {
    console.log("Clicked");
  };

  return <button onClick={handleClick}>Click</button>;
}

Native DOM Example

const button = document.getElementById("btn");

button.addEventListener("click", () => {
  console.log("Clicked");
});

Summary

React uses Synthetic Events and JSX event props like onClick, providing a consistent, cross-browser event system. Native DOM events use browser APIs such as addEventListener() and work directly with the real DOM.

25. What is event pooling and how has it changed in modern React?

Event pooling was an optimization used in older React versions where Synthetic Event objects were reused for better performance. After an event handler finished, React cleared the event object's properties, making them unavailable in asynchronous code.

Older React

function handleClick(event) {
  setTimeout(() => {
    console.log(event.target); // May be null
  }, 1000);
}

To keep the event, you had to use:

event.persist();

Modern React (React 17+)

Event pooling was removed.

function handleClick(event) {
  setTimeout(() => {
    console.log(event.target); // Works correctly
  }, 1000);
}

No need for event.persist() anymore.

Why Was It Removed?

  • Modern browsers are more efficient with memory

  • Event pooling added complexity

  • It often confused developers

Summary: Older React versions reused and cleared Synthetic Events through event pooling. React 17+ removed this behavior, so event objects remain available even in asynchronous code.

26. What are hooks in React?

Hooks are special React functions that let functional components use features like state, lifecycle behavior, and context without needing class components. They make code simpler and allow logic to be reused across components.

Common Hooks

  • useState – Manage state

  • useEffect – Handle side effects

  • useContext – Access context data

  • useRef – Access DOM elements or store values

  • useMemo – Memoize computed values

  • useCallback – Memoize functions

Example

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

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

Benefits

  • Simpler than class components

  • No this keyword

  • Reusable logic through custom Hooks

  • Cleaner and more maintainable code

Summary: Hooks are functions that let functional components use React features such as state and lifecycle behavior, making them the standard approach in modern React.

27. Why were hooks introduced?

Hooks were introduced to let functional components use state and lifecycle features without needing class components. They solve problems such as complex class-based code, this binding issues, and difficulty reusing stateful logic between components.

Problems Hooks Solve

  • Reduce the need for class components

  • Eliminate this keyword confusion

  • Make components simpler and easier to read

  • Enable reusable logic through custom Hooks

  • Avoid deeply nested patterns like Higher-Order Components (HOCs) and Render Props

Example

Before Hooks (Class Component):

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

With Hooks (Functional Component):

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

Summary: Hooks were introduced to make React code simpler, more reusable, and easier to maintain by bringing state and lifecycle features to functional components.

28. What are the rules of hooks?

Hooks must follow specific rules so React can track state and effects correctly.

Rule 1: Only Call Hooks at the Top Level

Do not call Hooks inside loops, conditions, or nested functions.

✅ Correct

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

❌ Incorrect

function Counter() {
  if (true) {
    const [count, setCount] = React.useState(0);
  }
}

Rule 2: Only Call Hooks in React Functions

Hooks can be used only in:

  • Functional components

  • Custom Hooks

✅ Correct

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

❌ Incorrect

function getData() {
  const [count, setCount] = React.useState(0);
}

Rule 3: Custom Hooks Must Start with use

function useCounter() {
  const [count, setCount] = React.useState(0);
  return { count, setCount };
}

Why These Rules Exist

React relies on the order of Hook calls during each render. Breaking the rules can cause React to associate state with the wrong Hook.

Summary: Always call Hooks at the top level, only inside React components or custom Hooks, and name custom Hooks with the use prefix.

29. What is useState?

useState is a React Hook used to add and manage state in functional components. It returns the current state value and a function to update that value.

Syntax

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

Example

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

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

How It Works

  • count → Current state value

  • setCount → Function to update the state

  • 0 → Initial state value

When setCount is called, React updates the state and re-renders the component.

Summary: useState lets functional components store and update data that can change over time, such as user input, counters, or form values.

30. How does state updating work in React?

State updates in React are asynchronous. When you call a state setter function (like setState or setCount), React schedules an update and then re-renders the component with the new state. React may also batch multiple state updates together to improve performance.

Example

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

  const handleClick = () => {
    setCount(count + 1);
  };

  return <button onClick={handleClick}>{count}</button>;
}

Updating Based on Previous State

Use the functional form when the new value depends on the previous value:

setCount(prevCount => prevCount + 1);

Why Use the Functional Form?

setCount(prev => prev + 1);
setCount(prev => prev + 1);

This correctly increases the count by 2.

Summary: React schedules state updates and re-renders the component with the new value. When the next state depends on the previous state, use the functional update form.