Insights into Company
← React

React Fundamentals

Understand the idea. Compare it. Explain it. Test yourself.

Question 1 of 5

What is React?

Solution and explanation

What it is

React is a JavaScript library for building user interfaces out of components. You describe what the screen should look like for the current data (state and props), and React works out the smallest set of DOM changes needed to get there. It was released by Facebook (Meta) in 2013 and is used by Facebook, Instagram, Netflix, Swiggy, Flipkart and most modern dashboards.

  • **Declarative:** you write if (loading) return <Spinner/>, not "find the div, remove its children, append a spinner".
  • **Component-based:** a page is a tree of small, reusable pieces (<JobCard>, <SearchBar>, <Pagination>).
  • **One-way data flow:** data goes down from parent to child through props; children ask parents to change data through callback props.
  • **Library, not framework:** React only handles the view. Routing (React Router), data fetching (TanStack Query), forms and global state come from other libraries or frameworks such as Next.js.

A first component

import { useState } from 'react';

export default function JobCounter() {
  const [applied, setApplied] = useState(0);
  return (
    <div className="card">
      <p>You applied to {applied} jobs today</p>
      <button onClick={() => setApplied(applied + 1)}>Apply</button>
    </div>
  );
}

Each click calls setApplied; React re-runs the function, compares the new output with the old one and updates only the text inside <p>.

How rendering works

  1. **Render:** React calls your component functions to get a tree of elements.
  2. **Reconcile:** it compares (diffs) the new tree with the previous one.
  3. **Commit:** it applies the minimal DOM changes, then runs effects.

Interview points

  • React is a UI library; Angular is a full framework with DI, router and forms built in.
  • It is fast mainly because it batches updates and touches the real DOM as little as possible.
  • React 18 added concurrent rendering (startTransition), automatic batching and streaming SSR.

Summary

React = components + state + declarative rendering. You describe the UI for each state, and React keeps the DOM in sync.

Practice explaining this
Question 2 of 5

What is JSX?

Solution and explanation

What it is

JSX (JavaScript XML) is a syntax extension that lets you write HTML-like markup inside JavaScript. Browsers do not understand JSX; a compiler (Babel, SWC, esbuild through Vite) turns it into plain function calls.

const el = <h1 className="title">Hello {user.name}</h1>;

compiles to

const el = jsx('h1', { className: 'title', children: ['Hello ', user.name] });

So JSX is just a nicer way of creating React elements, which are plain objects describing what to render.

Rules of JSX

  • Return **one root element**; wrap siblings in a <div> or a fragment <>...</>.
  • Use className instead of class, htmlFor instead of for, camelCase events (onClick).
  • Close every tag: <img />, <input />.
  • { } holds any JavaScript **expression** (not statements): variables, function calls, ternaries, map.
  • Inline styles are objects: style={{ color: 'red', fontSize: 14 }}.

Conditional rendering and lists

function JobList({ jobs, loading }) {
  if (loading) return <p>Loading…</p>;
  return (
    <>
      {jobs.length === 0 && <p>No jobs found</p>}
      <ul>
        {jobs.map(job => (
          <li key={job.id}>
            {job.title} {job.remote ? '(Remote)' : `(${job.city})`}
          </li>
        ))}
      </ul>
    </>
  );
}

The key must be a stable, unique id so React can match list items between renders. Using the array index breaks when items are inserted, removed or sorted.

Security

JSX escapes values automatically, so {comment} containing <script> is shown as text, which prevents XSS. Only dangerouslySetInnerHTML bypasses this; sanitise the HTML (DOMPurify) before using it.

Summary

JSX is syntactic sugar for React.createElement/jsx() calls: HTML-like, but with JavaScript expressions in braces, camelCase attributes and automatic escaping.

Practice explaining this
Question 3 of 5

What are components?

Solution and explanation

What they are

A component is a reusable, self-contained piece of UI. In modern React a component is a **function** that receives props and returns JSX. Component names start with a capital letter so React can tell <JobCard> (component) from <div> (HTML tag).

function JobCard({ title, company, salary, onApply }) {
  return (
    <article className="job-card">
      <h3>{title}</h3>
      <p>{company}</p>
      {salary && <p>₹{salary.toLocaleString('en-IN')} per year</p>}
      <button onClick={onApply}>Apply</button>
    </article>
  );
}

function JobsPage({ jobs }) {
  return jobs.map(j => <JobCard key={j.id} {...j} onApply={() => apply(j.id)} />);
}

Function versus class components

Function componentClass component
Syntaxplain functionclass X extends React.Component with render()
StateuseState, useReducerthis.state, this.setState
LifecycleuseEffectcomponentDidMount, componentDidUpdate, componentWillUnmount
Todayrecommendedlegacy code; still needed for error boundaries

Kinds of components

  • **Presentational:** only display props (<Avatar>, <Badge>).
  • **Container/smart:** fetch data and hold state, then pass it to presentational children.
  • **Layout:** arrange children (<Sidebar>, <Grid>) using the children prop.
  • **Composition over inheritance:** React never extends components; you combine them.
function Card({ title, children }) {
  return <section className="card"><h2>{title}</h2>{children}</section>;
}
<Card title="Profile"><ProfileForm /></Card>

Good component design

  • One responsibility per component; split when a file grows past ~200 lines.
  • Keep components pure: same props give the same output, no side effects during render.
  • Lift shared state to the nearest common parent.

Summary

Components are functions from props to UI. Build pages by composing small, pure, reusable components.

Practice explaining this
Question 4 of 5

Props versus state?

Solution and explanation

The difference

PropsState
Ownerthe parentthe component itself
Changeable by the component?no, read-onlyyes, through its setter
Purposeconfigure a childremember data that changes over time
Causes re-render when changedyes (parent re-renders with new props)yes

**Props** are arguments passed into a component, like function parameters. **State** is the component's own memory, kept by React between renders.

Example

function SalaryFilter({ min, onChange }) {          // min and onChange are props
  return <input type="number" value={min} onChange={e => onChange(Number(e.target.value))} />;
}

function JobSearch() {
  const [minSalary, setMinSalary] = useState(0);    // state lives here
  return (
    <>
      <SalaryFilter min={minSalary} onChange={setMinSalary} />
      <Results minSalary={minSalary} />
    </>
  );
}

JobSearch owns the state. Both children receive it as props. When the input changes, the child calls onChange, the parent updates its state, and both children re-render with the new value. This is **one-way data flow**.

Rules

  • Never modify props: props.title = 'x' is a bug.
  • Never modify state directly: state.items.push(x) does not re-render; create a new array: setItems([...items, x]).
  • Do not copy props into state (useState(props.value)) unless you really want an initial value only; the state will not follow later prop changes.
  • Keep state minimal: compute derived values (filteredJobs, total) during render instead of storing them.

Summary

Props flow down and are read-only; state is local, mutable through setters, and triggers re-renders. Shared data is held as state in a common parent and passed down as props.

Practice explaining this
Question 5 of 5

What is the virtual DOM?

Solution and explanation

What it is

The virtual DOM is a lightweight JavaScript object tree that describes the UI. When state changes, React builds a new tree, compares it with the previous tree (**diffing** or **reconciliation**) and applies only the differences to the real browser DOM.

Real DOM operations (layout, paint) are expensive; comparing plain objects in memory is cheap. Batching many changes into one minimal DOM update keeps the page fast.

How the diff works

React's algorithm is O(n) thanks to two assumptions:

  1. **Different element types produce different trees.** <div> replaced by <section> destroys the old subtree and builds a new one (state inside is lost).
  2. **Keys identify list items.** With key={job.id}, React knows which item moved, was added or removed.
// Before: [A, B, C]   After: [Z, A, B, C]
{jobs.map(j => <JobRow key={j.id} job={j} />)}   // React inserts one row
{jobs.map((j, i) => <JobRow key={i} job={j} />)} // React thinks every row changed

Render and commit phases

  • **Render phase:** call components, build the new virtual tree, diff. Can be paused or restarted in React 18 (concurrent rendering).
  • **Commit phase:** apply DOM mutations, run useLayoutEffect, then useEffect. Never interrupted.

Fiber

Since React 16 the reconciler is called **Fiber**. Each element becomes a fiber node that represents a unit of work, which lets React split rendering into chunks, prioritise urgent updates (typing) over less urgent ones (rendering a big list) and resume work later.

Common misconception

The virtual DOM is not "faster than the DOM" by itself; hand-written DOM code can be faster. Its benefit is that you write simple declarative code and still get reasonably minimal updates.

Summary

Virtual DOM = in-memory UI tree. React diffs old and new trees using element types and keys, then commits the minimal changes to the real DOM.

Practice explaining this