React Interview Questions and Answers (2025)

author image Hirely
at 08 Jan, 2025

Question: What is the difference between state and props in React?

Answer:

In React, state and props are both used to manage data within components, but they serve different purposes and have distinct characteristics. Here’s a breakdown of the differences:

  1. Definition:

    • State: Represents data or variables that are local to a component and can change over time. State is used to store information that can change dynamically and trigger a re-render of the component.
    • Props: Short for “properties,” props are used to pass data from a parent component to a child component. Props are immutable, meaning that a child component cannot modify the props it receives from its parent.
  2. Mutability:

    • State: State is mutable, meaning it can be changed within the component using the setState() method (for class components) or useState() hook (for functional components). When the state changes, React re-renders the component.
    • Props: Props are immutable. Once a parent component sets the props of a child component, the child cannot modify them. Props can only be changed by the parent component, and any changes to props cause the child component to re-render.
  3. Usage:

    • State: Used to store data that is local and can change during the lifecycle of a component. For example, form inputs, toggling visibility of UI elements, or tracking user interactions.
    • Props: Used to pass data or configuration from a parent component to a child component. For example, passing user information, labels, or event handlers to child components.
  4. Lifecycle:

    • State: State is part of the component’s internal lifecycle. It can change based on user input, API responses, or other triggers.
    • Props: Props are managed by the parent component, and they are passed down to child components. The child does not control props, and any changes to the props (by the parent) trigger a re-render of the child.
  5. Example:

    // Example using state
    class Counter extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          count: 0
        };
      }
    
      increment = () => {
        this.setState({ count: this.state.count + 1 });
      };
    
      render() {
        return (
          <div>
            <p>Count: {this.state.count}</p>
            <button onClick={this.increment}>Increment</button>
          </div>
        );
      }
    }
    
    // Example using props
    const UserGreeting = (props) => {
      return <h1>Hello, {props.name}!</h1>;
    };
    
    // Parent component passing props
    const App = () => {
      return <UserGreeting name="Alice" />;
    };
    • In this example, the Counter component uses state to track the count and update it when the button is clicked.
    • The UserGreeting component uses props to receive a name and display it, but it doesn’t modify it.
  6. Where they are used:

    • State is often used for data that needs to be changed or updated based on user interaction or external events.
    • Props are typically used for configuration or data that is passed from parent components to child components.

Summary of Differences:

FeatureStateProps
MutabilityMutable (can be changed within the component)Immutable (cannot be changed by the child component)
OwnershipOwned by the component where it’s definedPassed down from parent to child components
UsageUsed for data that changes over time (local to a component)Used to pass data from parent to child components
LifecycleManaged and updated by the component (e.g., setState)Managed by the parent component
Re-renderTriggers re-render when state changesTriggers re-render when props change

In essence, state is for data that belongs to and is managed by the component itself, while props are for data passed down from a parent component to a child component.

Question: What is JSX?

Answer:

JSX (JavaScript XML) is a syntax extension for JavaScript, commonly used with React to describe what the user interface should look like. It allows you to write HTML-like code within JavaScript, making it easier to create and visualize React components. JSX simplifies the process of creating complex UIs by combining the structure (HTML) and logic (JavaScript) in a single place.

Key features of JSX:

  1. HTML-Like Syntax:

    • JSX lets you write markup (HTML) directly within your JavaScript code. This makes React components easier to understand because you can see both the UI structure and the logic in the same file.
    • Example JSX code:
      const element = <h1>Hello, world!</h1>;
      This creates a React element (<h1>Hello, world!</h1>) using JSX syntax.
  2. JSX is Transformed into JavaScript:

    • Browsers cannot directly interpret JSX, so tools like Babel are used to compile JSX into standard JavaScript. After compilation, JSX gets transformed into React.createElement() calls.
    • Example transformation:
      const element = <h1>Hello, world!</h1>;
      This JSX code is transformed into:
      const element = React.createElement('h1', null, 'Hello, world!');
  3. Embedded Expressions:

    • You can embed JavaScript expressions inside JSX by wrapping them in curly braces {}. This allows you to insert dynamic content into your JSX.
    • Example:
      const name = 'Alice';
      const element = <h1>Hello, {name}!</h1>;
      In this example, the value of name will be dynamically inserted into the JSX.
  4. Attributes in JSX:

    • JSX allows you to pass attributes (similar to HTML attributes) to elements. These attributes are camelCased in JSX (e.g., className instead of class, htmlFor instead of for).
    • Example:
      const element = <div className="container">Content here</div>;
  5. JSX Requires a Single Parent Element:

    • JSX requires that all elements inside a component must be wrapped in a single parent element. If you want to return multiple elements, you can use a Fragment or a div element to group them together.

    • Example:

      // Valid JSX
      const element = (
        <div>
          <h1>Hello</h1>
          <p>Welcome to React!</p>
        </div>
      );
      // Using Fragment (no additional HTML element)
      const element = (
        <>
          <h1>Hello</h1>
          <p>Welcome to React!</p>
        </>
      );
  6. Event Handling in JSX:

    • JSX allows you to handle events in a declarative way. For example, to handle a click event, you would pass a function as a prop to an element’s onClick attribute.
    • Example:
      const handleClick = () => {
        alert('Button clicked!');
      };
      
      const element = <button onClick={handleClick}>Click me</button>;

Summary:

JSX makes it easier to write and manage React components by combining HTML-like syntax with JavaScript logic. While it may look like HTML, it gets transformed into JavaScript that React can understand and render efficiently. By using JSX, developers can write more readable, concise, and maintainable React code.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as ReactJS interview questions, ReactJS interview experiences, and details about various ReactJS job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now