React Interview Questions for Freshers (2026): 55+ Questions with Answers, Hooks, Code, Output Puzzles and Mini-Build Tasks

What React interview questions are asked to freshers? Most fresher interviews focus on seven areas: what React is and how JSX works, components, props vs state, hooks (useState, useEffect and a few more), lists and keys, forms and events, and calling an API, often a Java Spring Boot backend for full stack roles. Interviewers also give small tasks such as building a counter, a to-do list or a data list with loading and error states. If you can explain these with short code examples, you’re well prepared.

This guide from VibrantMinds Technologies in Pune covers 55+ React JS interview questions and answers in a consistent format: an interview-ready answer, a code example and a common trap. It also includes output puzzles, React with Spring Boot integration, mini-build tasks, project ideas, a 14-day plan and mistakes to avoid. If you’ve been searching for React interview questions for freshers, React JS interview questions and answers, React hooks interview questions, React useState and useEffect explained, React props vs state, React coding interview questions for freshers, React with Spring Boot integration or free IT job WhatsApp groups for freshers in Pune, this is built to be the complete answer.

React evolves, and newer versions add features. This guide focuses on fundamentals that stay stable. Check the official React documentation for your version and ask which version a company uses. This guide avoids salary figures and unverified statistics.

KEY TAKEAWAYS (READ THIS FIRST)

Takeaway

Detail

Know the core five

JSX, components, props, state and hooks cover most fresher questions.

Props flow down, state lives inside

This one idea answers many “props vs state” and “lifting state” questions.

useEffect is the most misunderstood hook

Learn the dependency array well.

Never mutate state directly

Always create a new array or object when updating state.

Show an API call with loading and error states

This is the most common practical task.

JavaScript fundamentals matter

Closures, map, filter, arrow functions and async/await appear constantly in React interviews.

Be honest about your level

Say what you’ve built and what you’re still learning.

HOW REACT INTERVIEWS USUALLY FLOW




TOPIC MAP: WHAT TO PREPARE (BY PRIORITY)

This is a guide, not data. It shows where freshers should spend time.




SECTION 1: REACT BASICS AND JSX (Q1 TO Q10)

Q1. What is React?
Interview-ready answer: React is a JavaScript library for building user interfaces from reusable components. It focuses on the view layer and updates the screen efficiently when data changes.
Trap: calling React a “framework”. It’s commonly described as a library, though people use the terms loosely. Be consistent.

Q2. Why use React? What are its advantages?
Answer: Reusable components, a declarative style (you describe what the UI should look like for a given state), efficient updates through the virtual DOM, a large ecosystem and community, and a clear one-way data flow.

Q3. What is JSX?
Answer: JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. It is compiled into regular JavaScript function calls by build tools.

jsx

const element = <h1>Hello, {name}</h1>;
const element = <h1>Hello, {name}</h1>;
const element = <h1>Hello, {name}</h1>;

Q4. JSX rules you must remember

  • Return one parent element (or a Fragment <>...</>)

  • Use className instead of class, and htmlFor instead of for

  • Close all tags, including <img /> and <input />

  • Put JavaScript expressions inside { }

  • Component names start with a capital letter

Q5. What is the virtual DOM and how does React use it?
Answer: The virtual DOM is a lightweight in-memory representation of the UI. When state changes, React builds a new virtual tree, compares it with the previous one (this process is called reconciliation) and updates only the parts of the real DOM that changed.

Q6. Real DOM vs virtual DOM?

Point

Real DOM

Virtual DOM

What it is

The browser’s actual page structure

A JavaScript object copy used by React

Updates

Direct changes can be costly

React batches and applies minimal changes

Used by

Browser

React

Q7. What is a Fragment and why use it?
Answer: A Fragment (<React.Fragment> or <>...</>) groups elements without adding an extra node to the DOM.

Q8. How do you start a new React project?
Answer: Many developers use a modern build tool such as Vite. The React team has moved away from recommending Create React App for new projects, so check the current official guidance.

bash

npm create vite@latest my-app -- --template react
cd my-app
npm install
npm

npm create vite@latest my-app -- --template react
cd my-app
npm install
npm

npm create vite@latest my-app -- --template react
cd my-app
npm install
npm

Q9. What is the difference between an element and a component?
Answer: An element is a plain description of what to show (the result of JSX). A component is a function (or class) that returns elements and can accept props.

Q10. What is a single-page application (SPA)?
Answer: An application that loads one HTML page and updates content dynamically using JavaScript, often with client-side routing, rather than loading a new page for every action.

SECTION 2: COMPONENTS, PROPS AND STATE (Q11 TO Q20)

Q11. Functional vs class components?
Answer: Functional components are JavaScript functions that return JSX and use hooks for state and lifecycle behaviour. Class components use this, render() and lifecycle methods. Modern React code mostly uses functional components, but you may meet class components in older projects.

Q12. What are props?
Answer: Props (properties) are inputs passed from a parent component to a child. They are read-only in the child.

jsx

function Welcome({ name }) {
  return <h2>Hello, {name}</h2>;
}

function App() {
  return <Welcome name="Amit" />;
}
function Welcome({ name }) {
  return <h2>Hello, {name}</h2>;
}

function App() {
  return <Welcome name="Amit" />;
}
function Welcome({ name }) {
  return <h2>Hello, {name}</h2>;
}

function App() {
  return <Welcome name="Amit" />;
}

Q13. What is state?
Answer: State is data owned by a component that can change over time. When state changes, React re-renders the component.

Q14. Props vs state: the difference

Point

Props

State

Owned by

Parent component

The component itself

Mutable by the component?

No (read-only)

Yes, through the setter function

Purpose

Pass data and callbacks down

Manage changing data inside a component

Triggers re-render when changed

Yes, when the parent re-renders with new props

Yes

Trap: saying “props are immutable, state is mutable” without mentioning that you update state through the setter and never by direct mutation.

Q15. What is the children prop?
Answer: Whatever you place between a component’s opening and closing tags is passed as props.children, which is useful for layouts and wrappers.

jsx

function Card({ children }) {
  return <div className="card">{children}</div>;
}
<Card><p>Inside the card</p></Card>
function Card({ children }) {
  return <div className="card">{children}</div>;
}
<Card><p>Inside the card</p></Card>
function Card({ children }) {
  return <div className="card">{children}</div>;
}
<Card><p>Inside the card</p></Card>

Q16. What is “lifting state up”?
Answer: When two components need the same data, move the state to their closest common parent and pass it down as props, along with callbacks to update it.

Q17. What is props drilling and how can you avoid it?
Answer: Passing props through many intermediate components that don’t use them. You can reduce it with component composition, the Context API or a state management library.

Q18. What is the difference between controlled and uncontrolled components?
Answer: In a controlled component, form data is handled by React state (value and onChange). In an uncontrolled component, the DOM holds the data and you read it with a ref when needed.

Q19. How do you handle events in React?
Answer: Using camelCase event props with function handlers, such as onClick and onChange. React wraps native events in a cross-browser synthetic event.

jsx

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

Q20. What is conditional rendering?
Answer: Showing different UI depending on a condition.

jsx

{isLoggedIn ? <Dashboard /> : <Login />}
{error && <p className="error">{error}</p>}
{isLoggedIn ? <Dashboard /> : <Login />}
{error && <p className="error">{error}</p>}
{isLoggedIn ? <Dashboard /> : <Login />}
{error && <p className="error">{error}</p>}

Trap: using {count && <List />} when count can be 0, which renders 0 on screen. Use count > 0 && <List />.

SECTION 3: HOOKS (Q21 TO Q34)

Q21. What are hooks and what rules must you follow?
Answer: Hooks are functions that let functional components use state and other React features. The rules: call hooks only at the top level of a component or custom hook (not inside loops, conditions or nested functions) and only from React functions.

Q22. Explain useState with an example.

jsx

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}
import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}
import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

Q23. Why should you use the functional update form of setState?
Answer: When the new state depends on the previous state, use setCount(prev => prev + 1). This avoids stale values when several updates are batched together.

Q24. Why shouldn’t you modify state directly?
Answer: React detects changes by comparing references. Mutating an existing array or object keeps the same reference, so React may not re-render. Create a new copy instead.

jsx

// Wrong
items.push(newItem);
setItems(items);

// Right
setItems([...items, newItem]);
// Wrong
items.push(newItem);
setItems(items);

// Right
setItems([...items, newItem]);
// Wrong
items.push(newItem);
setItems(items);

// Right
setItems([...items, newItem]);

Q25. How do you update an object or array in state?

jsx

setUser({ ...user, name: "Rahul" });                         // update an object field
setItems(items.filter(i => i.id !== id));                    // remove an item
setItems(items.map(i => i.id === id ? { ...i, done: true } : i));   // update one item
setUser({ ...user, name: "Rahul" });                         // update an object field
setItems(items.filter(i => i.id !== id));                    // remove an item
setItems(items.map(i => i.id === id ? { ...i, done: true } : i));   // update one item
setUser({ ...user, name: "Rahul" });                         // update an object field
setItems(items.filter(i => i.id !== id));                    // remove an item
setItems(items.map(i => i.id === id ? { ...i, done: true } : i));   // update one item

Q26. What is useEffect and when does it run?
Answer: useEffect runs side effects (data fetching, subscriptions, timers, updating the document title) after the component renders. When it runs depends on the dependency array.

Dependency array

When the effect runs

Not provided

After every render

[]

Once after the first render

[a, b]

After the first render and whenever a or b changes

Q27. Explain the useEffect cleanup function.
Answer: The function you return from an effect runs before the effect re-runs and when the component unmounts. Use it to clear timers, unsubscribe or cancel requests.

jsx

useEffect(() => {
  const id = setInterval(() => console.log("tick"), 1000);
  return () => clearInterval(id);       // cleanup
}, []);
useEffect(() => {
  const id = setInterval(() => console.log("tick"), 1000);
  return () => clearInterval(id);       // cleanup
}, []);
useEffect(() => {
  const id = setInterval(() => console.log("tick"), 1000);
  return () => clearInterval(id);       // cleanup
}, []);

Q28. How do you fetch data with useEffect? Show loading and error handling.

js

import { useState, useEffect } from "react";

function StudentList() {
  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch("http://localhost:8080/api/students")
      .then(res => {
        if (!res.ok) throw new Error("Failed to load students");
        return res.json();
      })
      .then(data => setStudents(data))
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {students.map(s => <li key={s.id}>{s.name}</li>)}
    </ul>
  );
}
import { useState, useEffect } from "react";

function StudentList() {
  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch("http://localhost:8080/api/students")
      .then(res => {
        if (!res.ok) throw new Error("Failed to load students");
        return res.json();
      })
      .then(data => setStudents(data))
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {students.map(s => <li key={s.id}>{s.name}</li>)}
    </ul>
  );
}
import { useState, useEffect } from "react";

function StudentList() {
  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch("http://localhost:8080/api/students")
      .then(res => {
        if (!res.ok) throw new Error("Failed to load students");
        return res.json();
      })
      .then(data => setStudents(data))
      .catch(err => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {students.map(s => <li key={s.id}>{s.name}</li>)}
    </ul>
  );
}

Q29. What causes an infinite loop with useEffect?
Answer: Updating state inside an effect that has no dependency array (or whose dependencies change on every render), which triggers a re-render and runs the effect again.

jsx

// Infinite loop
useEffect(() => { setCount(count + 1); });
// Infinite loop
useEffect(() => { setCount(count + 1); });
// Infinite loop
useEffect(() => { setCount(count + 1); });

Q30. What is useRef and when do you use it?
Answer: useRef returns a mutable object whose .current value persists across renders without causing re-renders. Common uses: accessing a DOM element and storing values such as timer IDs.

jsx

const inputRef = useRef(null);
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
const inputRef = useRef(null);
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
const inputRef = useRef(null);
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>

Q31. What is useContext?
Answer: It lets a component read a value from the nearest matching Context provider, avoiding props drilling for shared data such as theme or logged-in user.

Q32. What are useMemo and useCallback?
Answer: useMemo caches the result of an expensive calculation between renders. useCallback caches a function reference. Both depend on dependency arrays and are optimisations, so use them when there’s a real performance reason, not everywhere.

Q33. What is a custom hook?
Answer: A function whose name starts with use that reuses stateful logic across components.

jsx

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    fetch(url).then(r => r.json()).then(setData).finally(() => setLoading(false));
  }, [url]);
  return { data, loading };
}
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    fetch(url).then(r => r.json()).then(setData).finally(() => setLoading(false));
  }, [url]);
  return { data, loading };
}
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    fetch(url).then(r => r.json()).then(setData).finally(() => setLoading(false));
  }, [url]);
  return { data, loading };
}

Q34. What is useReducer?
Answer: A hook for managing more complex state logic using a reducer function and actions, similar to Redux’s pattern but local to the component.

SECTION 4: LISTS, KEYS, CONDITIONAL RENDERING AND FORMS (Q35 TO Q43)

Q35. How do you render a list?
Answer: Use map() and give each item a unique key

jsx

{todos.map(todo => <li key={todo.id}>{todo.text}</li>)}
{todos.map(todo => <li key={todo.id}>{todo.text}</li>)}
{todos.map(todo => <li key={todo.id}>{todo.text}</li>)}

Q36. Why are keys important? Can I use the index as a key?
Answer: Keys help React identify which items changed, were added or removed. Use a stable unique ID. Using the array index can cause bugs when the list can be reordered, filtered or modified, but it’s acceptable for static lists that never change.

Q37. How do you build a controlled form

jsx

function LoginForm() {
  const [form, setForm] = useState({ email: "", password: "" });

  const handleChange = (e) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

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

  return (
    <form onSubmit={handleSubmit}>
      <input name="email" value={form.email} onChange={handleChange} />
      <input name="password" type="password" value={form.password} onChange={handleChange} />
      <button type="submit">Login</button>
    </form>
  );
}
function LoginForm() {
  const [form, setForm] = useState({ email: "", password: "" });

  const handleChange = (e) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

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

  return (
    <form onSubmit={handleSubmit}>
      <input name="email" value={form.email} onChange={handleChange} />
      <input name="password" type="password" value={form.password} onChange={handleChange} />
      <button type="submit">Login</button>
    </form>
  );
}
function LoginForm() {
  const [form, setForm] = useState({ email: "", password: "" });

  const handleChange = (e) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

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

  return (
    <form onSubmit={handleSubmit}>
      <input name="email" value={form.email} onChange={handleChange} />
      <input name="password" type="password" value={form.password} onChange={handleChange} />
      <button type="submit">Login</button>
    </form>
  );
}

Q38. Why call e.preventDefault() in a form submit handler?
Answer: To stop the browser’s default full-page form submission so you can handle it in JavaScript.

Q39. How do you do basic form validation?
Answer: Check values in the submit handler (or on change), store error messages in state, and show them near the fields. Always validate again on the server.

Q40. How do you implement a search filter on a list?

jsx

const [query, setQuery] = useState("");
const filtered = students.filter(s =>
  s.name.toLowerCase().includes(query.toLowerCase())
);
const [query, setQuery] = useState("");
const filtered = students.filter(s =>
  s.name.toLowerCase().includes(query.toLowerCase())
);
const [query, setQuery] = useState("");
const filtered = students.filter(s =>
  s.name.toLowerCase().includes(query.toLowerCase())
);

Q41. How do you pass data from child to parent?
Answer: The parent passes a callback function as a prop, and the child calls it with the data.

jsx

function Child({ onSelect }) {
  return <button onClick={() => onSelect("Java")}>Pick Java</button>;
}
function Parent() {
  return <Child onSelect={(course) => console.log(course)} />;
}
function Child({ onSelect }) {
  return <button onClick={() => onSelect("Java")}>Pick Java</button>;
}
function Parent() {
  return <Child onSelect={(course) => console.log(course)} />;
}
function Child({ onSelect }) {
  return <button onClick={() => onSelect("Java")}>Pick Java</button>;
}
function Parent() {
  return <Child onSelect={(course) => console.log(course)} />;
}

Q42. How do you toggle a value (show/hide)?

jsx

const [show, setShow] = useState(false);
<button onClick={() => setShow(prev => !prev)}>Toggle</button>
{show && <p>Details</p>}
const [show, setShow] = useState(false);
<button onClick={() => setShow(prev => !prev)}>Toggle</button>
{show && <p>Details</p>}
const [show, setShow] = useState(false);
<button onClick={() => setShow(prev => !prev)}>Toggle</button>
{show && <p>Details</p>}

Q43. How do you handle multiple inputs with one handler?
Answer: Give each input a name and use [e.target.name]: e.target.value to update the matching state field (see Q37).

SECTION 5: ROUTING, CONTEXT AND STATE SHARING (Q44 TO Q50)

Q44. What is React Router and why use it?
Answer: A library for client-side routing in React apps, so different URLs show different components without a full page reload.

jsx

import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <nav><Link to="/">Home</Link> | <Link to="/students">Students</Link></nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/students" element={<StudentList />} />
        <Route path="/students/:id" element={<StudentDetail />} />
      </Routes>
    </BrowserRouter>
  );
}
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <nav><Link to="/">Home</Link> | <Link to="/students">Students</Link></nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/students" element={<StudentList />} />
        <Route path="/students/:id" element={<StudentDetail />} />
      </Routes>
    </BrowserRouter>
  );
}
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <nav><Link to="/">Home</Link> | <Link to="/students">Students</Link></nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/students" element={<StudentList />} />
        <Route path="/students/:id" element={<StudentDetail />} />
      </Routes>
    </BrowserRouter>
  );
}

Route APIs can differ between router versions, so check the documentation for your version.

Q45. How do you read a URL parameter

jsx

import { useParams } from "react-router-dom";
const { id } = useParams();
import { useParams } from "react-router-dom";
const { id } = useParams();
import { useParams } from "react-router-dom";
const { id } = useParams();

Q46. How do you navigate programmatically?

jsx

import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/students");
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/students");
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/students");

Q47. What is the Context API? Show a small example.

jsx

const ThemeContext = createContext("light");

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <p>Theme: {theme}</p>;
}
const ThemeContext = createContext("light");

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <p>Theme: {theme}</p>;
}
const ThemeContext = createContext("light");

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <p>Theme: {theme}</p>;
}

Q48. Context API vs Redux?
Answer: Context is built into React and works well for sharing simple, infrequently changing data. Redux (or similar libraries) provides a structured store, tooling and patterns for larger, more complex state. For a fresher project, Context plus hooks is often enough.

Q49. How do you protect a route (for example, a dashboard)?
Answer: Create a wrapper component that checks whether the user is logged in and either renders the page or redirects to the login route.

Q50. Where do you store a login token?
Answer: This is a design decision with security trade-offs. Options include memory, localStorage or secure cookies. Be aware that storing tokens in localStorage can expose them to cross-site scripting attacks, so explain the trade-off and the approach used in your project.

SECTION 6: PERFORMANCE AND GOOD PRACTICE (Q51 TO Q55)

Q51. How can you prevent unnecessary re-renders?
Answer: Keep state close to where it’s used, split large components, use React.memo for pure components, and use useMemo and useCallback where they help. Measure before optimising.

Q52. What is React.memo?
Answer: A wrapper that skips re-rendering a component if its props haven’t changed (using a shallow comparison).

Q53. What does StrictMode do?
Answer: A development tool that highlights potential problems. In development it may run certain functions (and effects) twice to help detect side-effect bugs. It doesn’t affect production builds.

Q54. What is code splitting and lazy loading?
Answer: Loading parts of the app only when needed, using React.lazy and Suspense, which reduces the initial bundle size.

Q55. How do you structure a React project?
Answer: A common approach is folders such as components, pages, hooks, services (API calls), context and utils. The structure should keep code organised and easy to find.




REACT WITH SPRING BOOT: CALLING YOUR JAVA BACKEND

For Java full stack roles, this section matters a lot.




Step 1: A simple Spring Boot endpoint

java

@RestController
@RequestMapping("/api/students")
public class StudentController {

    private final StudentService service;

    public StudentController(StudentService service) { this.service = service; }

    @GetMapping
    public List<StudentDto> all() { return service.findAll(); }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public StudentDto create(@Valid @RequestBody StudentDto dto) { return service.create(dto); }
}
@RestController
@RequestMapping("/api/students")
public class StudentController {

    private final StudentService service;

    public StudentController(StudentService service) { this.service = service; }

    @GetMapping
    public List<StudentDto> all() { return service.findAll(); }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public StudentDto create(@Valid @RequestBody StudentDto dto) { return service.create(dto); }
}
@RestController
@RequestMapping("/api/students")
public class StudentController {

    private final StudentService service;

    public StudentController(StudentService service) { this.service = service; }

    @GetMapping
    public List<StudentDto> all() { return service.findAll(); }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public StudentDto create(@Valid @RequestBody StudentDto dto) { return service.create(dto); }
}

Step 2: Allow the React origin (CORS)

java

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:5173")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:5173")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:5173")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

Vite’s dev server commonly runs on port 5173. Use the origin your own setup uses, and restrict origins properly in production.

Step 3: Call it from React (Axios example)

jsx

import axios from "axios";

export const getStudents = () => axios.get("http://localhost:8080/api/students");
export const addStudent = (student) => axios.post("http://localhost:8080/api/students", student);
import axios from "axios";

export const getStudents = () => axios.get("http://localhost:8080/api/students");
export const addStudent = (student) => axios.post("http://localhost:8080/api/students", student);
import axios from "axios";

export const getStudents = () => axios.get("http://localhost:8080/api/students");
export const addStudent = (student) => axios.post("http://localhost:8080/api/students", student);

Common integration questions

Question

Short answer

“Why do I get a CORS error?”

The browser blocks cross-origin responses unless the backend allows the origin. Configure CORS on Spring Boot.

“How do you send JSON?”

Send the object with Content-Type: application/json. Axios does this automatically for objects.

“How do you show server validation errors?”

Return 400 with messages, catch the error in React and display it near the fields.

“How do you handle login?”

Backend issues a token or session after authentication. The client sends it with later requests. Explain your project’s approach and its security trade-offs.

“fetch vs Axios?”

fetch is built into browsers. Axios is a library with conveniences such as automatic JSON handling and interceptors. Either is fine.

OUTPUT PUZZLES (TRY BEFORE READING THE ANSWER)

Puzzle 1: Two updates, one click

jsx

const [count, setCount] = useState(0);
function handleClick() {
  setCount(count + 1);
  setCount(count + 1);
}
const [count, setCount] = useState(0);
function handleClick() {
  setCount(count + 1);
  setCount(count + 1);
}
const [count, setCount] = useState(0);
function handleClick() {
  setCount(count + 1);
  setCount(count + 1);
}

Result: each click increases count by 1, not 2, because both calls use the same count value from that render. Use setCount(prev => prev + 1) twice to get +2.

Puzzle 2: Mutating state

jsx

const [items, setItems] = useState([1, 2]);
function add() {
  items.push(3);
  setItems(items);
}
const [items, setItems] = useState([1, 2]);
function add() {
  items.push(3);
  setItems(items);
}
const [items, setItems] = useState([1, 2]);
function add() {
  items.push(3);
  setItems(items);
}

Result: the UI may not update, because the array reference is the same. Use setItems([...items, 3]).

Puzzle 3: Effect timing

jsx

useEffect(() => {
  console.log("effect ran");
}, []);
useEffect(() => {
  console.log("effect ran");
}, []);
useEffect(() => {
  console.log("effect ran");
}, []);

Result: runs once after the first render. In development with StrictMode, you may see it run twice, which is expected behaviour to help catch bugs.

Puzzle 4: Zero on screen

jsx

const items = [];
return <div>{items.length && <p>Has items</p>}</div>;
const items = [];
return <div>{items.length && <p>Has items</p>}</div>;
const items = [];
return <div>{items.length && <p>Has items</p>}</div>;

Result: it renders 0, because 0 && ... evaluates to 0. Use items.length > 0 && ....

Puzzle 5: Missing dependency

jsx

useEffect(() => {
  fetch(`/api/students/${id}`).then(r => r.json()).then(setStudent);
}, []);
useEffect(() => {
  fetch(`/api/students/${id}`).then(r => r.json()).then(setStudent);
}, []);
useEffect(() => {
  fetch(`/api/students/${id}`).then(r => r.json()).then(setStudent);
}, []);

Result: it fetches only once, so when id changes the data doesn’t refresh. Add id to the dependency array: [id].

MINI-BUILD TASKS INTERVIEWERS GIVE (PRACTISE ALL OF THESE)

Task

Skills it tests

Time to aim for

Counter with increase, decrease, reset

useState, events

5 minutes

To-do list (add, delete, mark done)

State arrays, keys, forms

15 to 20 minutes

Fetch and display a list with loading and error states

useEffect, async, conditional rendering

15 minutes

Search and filter a list

Derived data, controlled input

10 minutes

Toggle (dark/light or show/hide)

State, conditional rendering, CSS classes

10 minutes

Registration form with validation

Controlled form, error state

20 minutes

Tabs component

State, props, composition

15 minutes

Pagination of a list

State, slicing arrays

20 minutes

Tip while coding live: speak your plan first, write the simplest working version, then improve it, and mention edge cases.

REACT PROJECT IDEAS FOR FRESHERS (WITH A SPRING BOOT BACKEND)

Project

Features to build

Skills shown

Student management system

List, add, edit, delete, search, validation

CRUD, forms, REST API, CORS

Expense tracker

Add expenses, categories, totals, filter by month

State, derived data, charts (optional)

Job tracker

Track applications, status, notes

CRUD, filters, status updates

Book or library manager

Search, issue and return, availability

Relationships, routing

Blog or notes app

Create posts, tags, search, login

Auth flow, routing, forms

Make it interview-ready: add a README with screenshots, put the code on GitHub, and prepare a 3-minute walkthrough covering the architecture, one challenge you solved and what you’d improve. List only what you can explain.

COMMON MISTAKES FRESHERS MAKE IN REACT INTERVIEWS

Mistake

Why it hurts

Better approach

Mutating state directly

UI doesn’t update, shows weak fundamentals

Create new arrays and objects

Ignoring the dependency array

Stale data or infinite loops

Learn the three cases (none, [], [a])

Using index as key in dynamic lists

Subtle bugs

Use stable unique IDs

Not handling loading and error states

Looks unfinished

Always show both

Putting everything in one giant component

Hard to read and reuse

Split into smaller components

Not knowing JavaScript basics

React questions fall apart

Revise closures, map, filter, async/await

Copying a tutorial project

You can’t explain choices

Build your own variation

Using useMemo and useCallback everywhere

Adds complexity without a reason

Optimise only when needed

Claiming advanced skills (Redux, Next.js) without depth

Follow-up questions expose gaps

List what you can explain

Forgetting e.preventDefault() in forms

Page reloads

Handle submit correctly

14-DAY REACT INTERVIEW PREPARATION PLAN

Day

Focus

Task

1

JavaScript refresh

ES6, arrow functions, destructuring, spread, map, filter, async/await

2

Setup, JSX, components

Create a Vite project. Build 3 small components.

3

Props and state

Build a counter and a parent-child example with callbacks

4

Lists, keys, events

Build a to-do list

5

Forms

Build a controlled registration form with validation

6

useEffect

Fetch data from a public API with loading and error states

7

Revision and puzzles

Solve the 5 output puzzles without looking

8

Routing

Add React Router with a list page and a detail page

9

Context API

Add a theme or user context

10

Spring Boot integration

Connect your React app to a Spring Boot CRUD API and fix CORS

11

Project polish

Add search, error handling, a README and screenshots

12

Performance and structure

Learn React.memo, lazy loading and folder structure

13

Mock questions

Answer Q1 to Q55 aloud and note weak topics

14

Full mock interview

Explain your project for 3 minutes and complete one live mini-build task

MYTH VS REALITY

Myth

Reality

“React is the whole front end.”

It’s a UI library. You also need JavaScript, HTML, CSS and tooling knowledge.

“I must know Redux and Next.js to get a fresher job.”

Strong fundamentals (components, hooks, API calls) matter first. Add others later if the job needs them.

“Hooks are too hard.”

useState and useEffect cover most basic needs. Learn them with small examples.

“Java developers don’t need React.”

For full stack roles, front-end basics are often expected. Check the job description.

“Memorising answers is enough.”

Interviewers ask you to code and explain. Practise building.

“A tutorial project is enough.”

Be able to explain every decision and extend the project.

HOW VIBRANTMINDS HELPS FRESHERS PREPARE FOR REACT AND FULL STACK INTERVIEWS

VibrantMinds Technologies Pvt. Ltd. is a Pune-based IT training and placement support company. If you searched for VibrantMinds or VibrantMinds Technologies, here is what it offers:

  • Full Stack Java Development (about 4 to 6 months): Core Java, OOP, JDBC, SQL, Spring Boot, REST APIs, front-end basics, projects, aptitude and interview preparation. Please check the candidate portal for the latest syllabus and which front-end tools are covered.

  • Core Java (about 1 to 2 months), Software Testing (Manual + Automation) and Python & Data Science for other paths

  • Project practice: Build a full stack project from the browser to the database and learn to explain it

  • Interview preparation: Technical rounds, project rounds, HR rounds, aptitude, communication and mock interviews

  • Resume and LinkedIn guidance: Clear, honest profiles

  • Placement support: Screening, drive coordination and interview support. Check the campus-drives portal at https://candidates.vibrantminds.in/ for current openings.

  • Free WhatsApp job alert groups for fresher IT jobs and drives

  • Honesty first: VibrantMinds offers placement support, not a guaranteed job, and no legitimate recruiter should ask you to pay to be interviewed.

VibrantMinds works as a talent ecosystem connecting candidates, colleges and companies, with 1900+ partner colleges and 600+ hiring companies. Read more fresher job guidance here: https://candidates.vibrantminds.in/blog/fresher-jobs-pune-2026

VIBRANTMINDS COURSES AT A GLANCE

Course

Duration

Key topics

Full Stack Java Development

4 to 6 months

Core Java, OOP, JDBC, SQL, Spring Boot, REST APIs, front-end basics, projects, aptitude and interview preparation

Software Testing (Manual + Automation)

2 to 5 months

Test cases, STLC, bug tracking, SQL, Selenium basics

Core Java

1 to 2 months

Syntax, OOP, collections, exceptions, strings

Python & Data Science

2 to 4 months

Python basics, data handling, analysis fundamentals

Fees, syllabus and batch dates are on https://candidates.vibrantminds.in/. Please confirm them directly before enrolling.

THE VIBRANTMINDS PLACEMENT PIPELINE: SIX STEPS




REAL OUTCOMES: WHAT TO EXPECT AND WHAT NOT TO

Past students have shared positive feedback about the training and support, and have gone on to roles at companies such as Aress Software and Education Technologies, Saama Technologies and Three M Software. Results vary by candidate, skill level, effort and market conditions, so please confirm details directly with the VibrantMinds team. No one can honestly promise a guaranteed job.

JOIN FREE VIBRANTMINDS WHATSAPP GROUPS: FRESHER IT JOB UPDATES FOR PUNE AND INDIA

Looking for free WhatsApp groups for IT jobs, a Java WhatsApp group for freshers or a job updates WhatsApp group in India? The VibrantMinds groups share fresher IT openings, campus drives, walk-in interview alerts and interview preparation updates, free of charge. Join whichever group has space. All three carry the same type of updates.


Group

What it offers

Link

VibrantMinds Fresher IT Jobs, Group 1

Fresher openings, campus drives, walk-in alerts

https://chat.whatsapp.com/CUCS1derlmTFee2c9dyUHd

VibrantMinds Fresher IT Jobs, Group 2

Fresher openings, campus drives, walk-in alerts

https://chat.whatsapp.com/FvMf1fGYQYnHppQ8AwFX40

VibrantMinds Fresher IT Jobs, Group 3

Fresher openings, campus drives, walk-in alerts

https://chat.whatsapp.com/I7RNnGMkb2L8S8HibdyWpQ

Never pay to apply. Legitimate recruiters do not charge candidates for tests, interviews or offer letters. Do not share sensitive personal or financial details in any group chat.

FREQUENTLY ASKED QUESTIONS

1. What are the most asked React interview questions for freshers?
What React and JSX are, the virtual DOM, components, props vs state, hooks (useState, useEffect, useRef, useContext), lists and keys, controlled forms, conditional rendering, fetching data with loading and error states, React Router basics and the Context API. You may also be asked to build a small component live.

2. What is the difference between props and state in React?
Props are read-only inputs passed from a parent to a child. State is data owned by a component that can change over time through its setter function and triggers a re-render when it changes. Props flow down the component tree, while state lives inside a component.

3. How do I call a Spring Boot REST API from React?
Use fetch or Axios inside a useEffect (or an event handler) to call your endpoint, send and receive JSON, and store the result in state. Enable CORS on the Spring Boot side for your React origin, and handle loading and error states in the component.

4. How does the useEffect dependency array work?
With no array, the effect runs after every render. With an empty array [], it runs once after the first render. With [a, b], it runs after the first render and whenever a or b changes. Include every value the effect uses to avoid stale data, and return a cleanup function when needed.

5. Are there free WhatsApp groups for IT fresher jobs in Pune?
Yes. VibrantMinds runs free fresher IT job WhatsApp groups that share openings, campus drives and walk-in alerts. Join through the links above. Always verify any job post and never pay to apply.

CONCLUSION: BUILD, EXPLAIN AND CONNECT

The best preparation for React interview questions for freshers is to build small components yourself, understand props, state and hooks with examples, practise fetching data with loading and error states, connect a React front end to a Spring Boot API, and explain your project clearly. Follow the 14-day plan, solve the output puzzles, complete the mini-build tasks, and be honest about what you know.

If you’re in Pune and want structured Java full stack training with front-end basics, project practice, interview preparation and placement support, VibrantMinds Technologies is here to help.

Call to action:

VISIT OR CONTACT VIBRANTMINDS IN PUNE

Office Address

Viva Academy Building, Near St. Mary's Church & Petrol Pump Mumbai-Bangalore Highway, Warje, near to Karvenagar, Pune, Maharashtra 411058

Phone Number

+91 95035 79517

© 2025 VibrantMinds Technologies Pvt. Ltd All Right Reserved

Office Address

Viva Academy Building, Near St. Mary's Church & Petrol Pump Mumbai-Bangalore Highway, Warje, near to Karvenagar, Pune, Maharashtra 411058

Phone Number

+91 95035 79517

© 2025 VibrantMinds Technologies Pvt. Ltd All Right Reserved

Office Address

Viva Academy Building, Near St. Mary's Church & Petrol Pump Mumbai-Bangalore Highway, Warje, near to Karvenagar, Pune, Maharashtra 411058

Phone Number

+91 95035 79517

© 2025 VibrantMinds Technologies Pvt. Ltd All Right Reserved