Get Started
Fresher Masterclass: 50+ Q&A

React Foundation: 50+ Fresher Interview Questions & Answers (2026)

Kickstart your React career. 50+ essential questions covering JSX, components, state, props, and fundamental React hooks for entry-level roles.

interview-prep

1. What is React and what are its key features?

Answer: React is a JavaScript library for building user interfaces, created by Facebook. Key features include:

  • Component-Based Architecture: UI built from reusable components

  • Virtual DOM: Efficient updating by comparing virtual representations

  • Unidirectional Data Flow: Predictable state management

  • JSX: JavaScript syntax extension for writing HTML-like structures

  • Declarative UI: Describe what UI should look like for different states

2. What's the difference between Real DOM and Virtual DOM?

Answer:

Real DOMVirtual DOM
Updates slowlyUpdates faster
Direct HTML manipulationManipulates in memory
Creates new DOM on updateUpdates only changed nodes
DOM manipulation expensiveDOM manipulation lightweight
Can update HTML directlyCan't update HTML directly

3. What are Components in React?

Answer: Components are independent, reusable pieces of UI. They accept props as input and return React elements describing what should appear on screen. Two types:

  • Functional Components: JavaScript functions (preferred with hooks)

  • Class Components: ES6 classes with lifecycle methods

4. What is JSX?

Answer: JSX (JavaScript XML) is a syntax extension that allows writing HTML-like code in JavaScript. It gets transpiled to React.createElement() calls by Babel.

jsx
// JSX
const element = <h1>Hello, React!</h1>;

// Transpiled to:
const element = React.createElement('h1', null, 'Hello, React!');

5. What are Props in React?

Answer: Props (properties) are read-only inputs passed from parent to child components. They allow data flow between components and make components reusable.

jsx
// Parent Component
<UserProfile name="John" age={25} />

// Child Component
function UserProfile(props) {
  return <div>{props.name} is {props.age} years old</div>;
}

6. What is State in React?

Answer: State is a built-in object that contains data that may change over a component's lifetime. Unlike props, state is managed within the component and can be updated using setState() (class) or state hooks (function).

7. Differentiate between State and Props.

Answer:

StateProps
Mutable within componentImmutable (read-only)
Managed within componentPassed from parent component
Can be initialized and changedCan only be passed and received
Local to componentCan be passed to any component
Accessed via this.state (class) or useStateAccessed via this.props or function params

8. What are Controlled Components?

Answer: Controlled components are form elements whose value is controlled by React state. The component's state serves as the "single source of truth."

jsx
function ControlledInput() {
  const [value, setValue] = useState('');
  
  return (
    <input 
      type="text" 
      value={value} 
      onChange={(e) => setValue(e.target.value)} 
    />
  );
}

9. What are Uncontrolled Components?

Answer: Uncontrolled components store their own state internally using refs to access DOM values directly, similar to traditional HTML form elements.

jsx
function UncontrolledInput() {
  const inputRef = useRef(null);
  
  const handleSubmit = () => {
    console.log(inputRef.current.value);
  };
  
  return <input type="text" ref={inputRef} />;
}

10. What are React Hooks?

Answer: Hooks are functions that let you use state and other React features in functional components. Introduced in React 16.8, they allow functional components to have stateful logic without classes.

11. Explain the useState Hook.

Answer: useState is a hook that lets you add React state to functional components. It returns an array with two elements: the current state value and a function to update it.

jsx
const [count, setCount] = useState(0);
// count = current state (0)
// setCount = function to update state

12. Explain the useEffect Hook.

Answer: useEffect lets you perform side effects in functional components. It combines the functionality of componentDidMount, componentDidUpdate, and componentWillUnmount.

jsx
useEffect(() => {
  // Side effect code here
  console.log('Component mounted or updated');
  
  return () => {
    // Cleanup code (like componentWillUnmount)
  };
}, [dependency]); // Dependency array

13. What are Keys in React and why are they important?

Answer: Keys are special string attributes that help React identify which items have changed, been added, or removed. They should be stable, predictable, and unique among siblings.

jsx
{items.map(item => (
  <li key={item.id}>{item.name}</li>
))}

14. What is Reconciliation in React?

Answer: Reconciliation is React's algorithm for diffing one tree with another to determine which parts need to be changed. It's the process through which React updates the DOM by comparing the Virtual DOM with the previous version.

15. What are Fragments?

Answer: Fragments let you group a list of children without adding extra nodes to the DOM.

jsx
// Without Fragment
return (
  <div>
    <ChildA />
    <ChildB />
  </div>
);

// With Fragment
return (
  <>
    <ChildA />
    <ChildB />
  </>
);

Component Lifecycle (8 Questions)

16. Explain React Component Lifecycle Methods.

Answer: Lifecycle methods are special methods in class components that get called at different stages of a component's life:

Mounting:

  • constructor() - Initial setup

  • static getDerivedStateFromProps() - Rarely used

  • render() - Required, returns JSX

  • componentDidMount() - After mounting to DOM

Updating:

  • static getDerivedStateFromProps()

  • shouldComponentUpdate() - Performance optimization

  • render()

  • getSnapshotBeforeUpdate() - Capture DOM info

  • componentDidUpdate() - After updates

Unmounting:

  • componentWillUnmount() - Cleanup

17. What is componentDidMount()?

Answer: Called after a component is mounted to the DOM. Ideal for:

  • API calls

  • Setting up subscriptions

  • DOM manipulations

  • Adding event listeners

18. What is componentDidUpdate()?

Answer: Called after the component updates (except initial render). Receives previous props and state as parameters.

jsx
componentDidUpdate(prevProps, prevState) {
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

19. What is componentWillUnmount()?

Answer: Called right before a component is destroyed. Used for cleanup:

  • Canceling network requests

  • Removing event listeners

  • Clearing timers/intervals

20. What is shouldComponentUpdate()?

Answer: A performance optimization method that determines if a component should re-render. By default returns true. Can compare current vs next props/state.

jsx
shouldComponentUpdate(nextProps, nextState) {
  return this.props.color !== nextProps.color;
}

21. How do you perform API calls in React?

Answer: API calls are typically made in componentDidMount() (class) or useEffect() (function).

jsx
// Using useEffect
useEffect(() => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => setData(data));
}, []); // Empty array = run once on mount

22. What are Error Boundaries?

Answer: React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing.

jsx
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  
  componentDidCatch(error, errorInfo) {
    console.log(error, errorInfo);
  }
  
  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

23. How do you optimize React performance?

Answer:

  1. Use React.memo() for functional components

  2. Implement shouldComponentUpdate() for class components

  3. Use useMemo() and useCallback() hooks

  4. Code splitting with React.lazy() and Suspense

  5. Virtualize long lists with react-window or react-virtualized

  6. Avoid inline function definitions in render

  7. Use keys properly in lists


Hooks Deep Dive (10 Questions)

24. What is the Rules of Hooks?

Answer:

  1. Only Call Hooks at the Top Level - Don't call inside loops, conditions, or nested functions

  2. Only Call Hooks from React Functions - Call from React functional components or custom hooks

25. Explain the useContext Hook.

Answer: useContext accepts a context object and returns the current context value for that context.

jsx
const ThemeContext = React.createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Click me</button>;
}

26. Explain the useReducer Hook.

Answer: useReducer is an alternative to useState for managing complex state logic. It's similar to Redux pattern.

jsx
const [state, dispatch] = useReducer(reducer, initialState);

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    default:
      return state;
  }
}

27. Explain the useCallback Hook.

Answer: useCallback returns a memoized callback function that only changes if one of its dependencies changes.

jsx
const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b], // Dependencies
);

28. Explain the useMemo Hook.

Answer: useMemo returns a memoized value that only recomputes when dependencies change.

jsx
const expensiveValue = useMemo(() => {
  return computeExpensiveValue(a, b);
}, [a, b]); // Recomputes only when a or b changes

29. What is useRef Hook?

Answer: useRef returns a mutable ref object whose .current property is initialized to the passed argument. It persists for the full lifetime of the component.

jsx
const inputRef = useRef(null);

// Access DOM element
inputRef.current.focus();

30. Create a Custom Hook example.

Answer: Custom hooks are JavaScript functions whose name starts with "use" and can call other hooks.

jsx
function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : initialValue;
  });
  
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  
  return [value, setValue];
}

31. What is the purpose of dependency array in useEffect?

Answer: The dependency array controls when the effect runs:

  • [] - Runs once after initial render (mount)

  • [dep1, dep2] - Runs when any dependency changes

  • No array - Runs after every render

32. How to handle multiple states with useState?

Answer: Either use multiple useState calls or use an object state:

jsx
// Multiple state variables
const [name, setName] = useState('');
const [age, setAge] = useState(0);
const [email, setEmail] = useState('');

// Single object state
const [user, setUser] = useState({
  name: '',
  age: 0,
  email: ''
});

33. What is the difference between useMemo and useCallback?

Answer:

  • useMemo returns a memoized value (result of a function)

  • useCallback returns a memoized function


State Management (7 Questions)

34. What is Lifting State Up?

Answer: Moving shared state to the closest common ancestor of components that need it. This ensures a single source of truth.

jsx
function Parent() {
  const [count, setCount] = useState(0);
  
  return (
    <>
      <ChildA count={count} />
      <ChildB setCount={setCount} />
    </>
  );
}

35. What is Prop Drilling and how to avoid it?

Answer: Prop drilling is passing props through multiple intermediate components. Avoid using:

  1. Context API - For global state

  2. State management libraries - Redux, MobX

  3. Component composition - Render props, children

36. What is Context API?

Answer: Context provides a way to pass data through the component tree without passing props down manually at every level.

jsx
// Create Context
const UserContext = React.createContext();

// Provide Context
<UserContext.Provider value={currentUser}>
  <App />
</UserContext.Provider>

// Consume Context
const user = useContext(UserContext);

37. Compare Redux vs Context API.

Answer:

FeatureReduxContext API
PurposeFull state managementProp drilling solution
ComplexityHighLow
BoilerplateMoreLess
DevToolsExcellentBasic
MiddlewareYesNo
PerformanceOptimizedCan cause re-renders

38. What are Higher-Order Components (HOC)?

Answer: HOCs are functions that take a component and return a new component with enhanced functionality.

jsx
function withLoading(Component) {
  return function EnhancedComponent({ isLoading, ...props }) {
    if (isLoading) return <div>Loading...</div>;
    return <Component {...props} />;
  };
}

39. What are Render Props?

Answer: A technique for sharing code between components using a prop whose value is a function.

jsx
<DataProvider render={data => (
  <h1>Hello {data.target}</h1>
)} />

40. What is the difference between Element and Component?

Answer:

  • Element: Plain object describing what you want to see on screen

  • Component: Function or class that returns elements

jsx
// Element
const element = <h1>Hello</h1>;

// Component
const Component = () => <h1>Hello</h1>;

Advanced Concepts (10 Questions)

41. What is React Router?

Answer: React Router is the standard routing library for React. It enables navigation between views of different components.

jsx
import { BrowserRouter, Route, Switch } from 'react-router-dom';

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/about" component={About} />
  </Switch>
</BrowserRouter>

42. What is Code Splitting in React?

Answer: Code splitting divides your bundle into smaller chunks that can be loaded on demand, improving initial load time.

jsx
const OtherComponent = React.lazy(() => import('./OtherComponent'));

<Suspense fallback={<div>Loading...</div>}>
  <OtherComponent />
</Suspense>

43. What are React Portals?

Answer: Portals provide a way to render children into a DOM node that exists outside the parent component's DOM hierarchy.

jsx
ReactDOM.createPortal(
  child,
  document.getElementById('modal-root')
);

44. What is React.StrictMode?

Answer: StrictMode is a tool for highlighting potential problems in an application. It activates additional checks and warnings for its descendants.

jsx
<React.StrictMode>
  <App />
</React.StrictMode>

45. How to handle events in React?

Answer: React events are named using camelCase and pass functions as event handlers.

jsx
<button onClick={handleClick}>
  Click me
</button>

function handleClick(event) {
  event.preventDefault();
  console.log('Button clicked');
}

46. What is Synthetic Event in React?

Answer: React's cross-browser wrapper around the browser's native event. It normalizes events to work identically across all browsers.

47. What are Refs and when to use them?

Answer: Refs provide a way to access DOM nodes or React elements. Use cases:

  • Managing focus, text selection, or media playback

  • Triggering imperative animations

  • Integrating with third-party DOM libraries

48. What is Server-Side Rendering (SSR) in React?

Answer: SSR is rendering React components on the server and sending HTML to the browser. Benefits include:

  • Better SEO

  • Faster initial page load

  • Better performance on low-end devices

49. What are React.PureComponent?

Answer: PureComponent implements shouldComponentUpdate() with a shallow prop and state comparison, preventing unnecessary re-renders.

jsx
class MyComponent extends React.PureComponent {
  // Only re-renders if props/state shallowly change
}

50. What is React.memo()?

Answer: React.memo() is a higher-order component for functional components similar to PureComponent.

jsx
const MyComponent = React.memo(function MyComponent(props) {
  // Only re-renders if props change
});

Practical & Scenario-Based (5 Questions)

51. How would you handle forms in React?

Answer: Two approaches:

jsx
// Controlled Component Approach
function Form() {
  const [formData, setFormData] = useState({
    username: '',
    email: ''
  });

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

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

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

52. How to prevent component from re-rendering?

Answer:

  1. Use React.memo() for functional components

  2. Extend PureComponent for class components

  3. Implement shouldComponentUpdate()

  4. Use useMemo() and useCallback() hooks

  5. Optimize context usage to avoid unnecessary consumers

53. How to fetch data when component mounts?

Answer: Using useEffect with empty dependency array:

jsx
function DataFetcher() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch('https://api.example.com/data');
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, []); // Empty array = run once on mount

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  return <div>{JSON.stringify(data)}</div>;
}

54. How to optimize large lists in React?

Answer:

  1. Virtualization - Render only visible items

  2. Windowing - Using libraries like react-window

  3. Pagination - Load data in chunks

  4. Lazy loading - Load items as user scrolls

  5. Use keys properly - Stable, unique keys

55. How to share logic between components?

Answer:

  1. Custom Hooks - Most modern approach

  2. Higher-Order Components (HOC) - Wrap components

  3. Render Props - Share code via props

  4. Context API - Share global state/logic

  5. Component Composition - Pass components as props


Tips for Interview Success

  1. Understand Fundamentals Deeply: Don't just memorize, understand why

  2. Practice Coding Examples: Be ready for live coding exercises

  3. Explain Your Thought Process: Interviewers want to see how you think

  4. Know When to Use What: Understand trade-offs between different approaches

  5. Stay Updated: Know React 18+ features (Concurrent Features, Automatic Batching, etc.)

  6. Ask Clarifying Questions: Shows problem-solving mindset

  7. Be Honest: It's okay to say "I don't know, but here's how I'd find out"

#career

Ready to Build Your Resume?

Create a professional resume that stands out to recruiters with our AI-powered builder.

React Foundation: 50+ Fresher Interview Questions & Answers (2026) | Hirecta Interview Prep | Hirecta