Get Started
React 101: 50+ Q&A

51 Top React JS Basic Interview Questions for Beginners (2026)

Start from zero. Over 50 basic React JS interview questions covering the most important concepts for beginners, from JSX to the component lifecycle.

interview-prep

Core Concepts & Fundamentals (Questions 1-15)

1. What is React and why is it so popular?

Answer: React is an open-source JavaScript library developed by Facebook for building user interfaces, particularly single-page applications. Its popularity stems from:

  • Component-Based Architecture: Reusable UI components simplify development and maintenance

  • Virtual DOM: Efficient updates improve performance

  • Declarative Syntax: Makes code predictable and easier to debug

  • Rich Ecosystem: Extensive library support (React Router, Redux, etc.)

  • Strong Community: Backed by Facebook and millions of developers

  • Learn Once, Write Anywhere: Works with React Native for mobile development

2. What are the key differences between React and traditional JavaScript?

Answer:

AspectTraditional JavaScriptReact
DOM ManipulationDirect DOM manipulationVirtual DOM
UpdatesManual updatesAutomatic re-renders
Code StructureImperative (how to do)Declarative (what to show)
ReusabilityLimited code reuseComponent-based reusability
State ManagementManual state trackingBuilt-in state management

3. Explain the Virtual DOM and its advantages

Answer: The Virtual DOM is a lightweight JavaScript representation of the actual DOM. When state changes:

  1. React creates a new Virtual DOM tree

  2. Compares it with previous version (diffing)

  3. Calculates minimal changes needed

  4. Updates only those parts in the actual DOM

Advantages:

  • Performance: Minimizes expensive DOM operations

  • Efficiency: Batches multiple updates

  • Cross-platform: Can render to different environments

  • Simplified: Abstracts away direct DOM manipulation

4. What are React Components?

Answer: Components are independent, reusable pieces of UI. They accept inputs (props) and return React elements describing what should appear on screen. There are two types:

jsx
// Function Component (modern approach)
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

// Class Component (legacy)
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

5. What is JSX?

Answer: JSX (JavaScript XML) is a syntax extension that allows writing HTML-like code in JavaScript:

jsx
const element = <h1 className="greeting">Hello, world!</h1>;
// Gets compiled to:
const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

Key points:

  • Not HTML, but syntactic sugar for React.createElement()

  • Must have a single root element

  • Use className instead of class

  • JavaScript expressions inside {}

  • Close all tags (<br /> not <br>)

6. What are Props?

Answer: Props (properties) are read-only inputs passed to components:

jsx
// Parent component
function App() {
  return <User name="John" age={30} />;
}

// Child component
function User(props) {
  return <p>{props.name} is {props.age} years old</p>;
}

Characteristics:

  • Immutable (cannot be modified by child)

  • Pass data from parent to child

  • Can be any JavaScript type

7. What is State in React?

Answer: State represents data that changes over time within a component:

jsx
import { useState } from 'react';

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

8. Differentiate between Props and State

Answer:

AspectPropsState
MutabilityImmutableMutable
OwnershipPassed from parentManaged within component
PurposeConfigurationDynamic data
InitializationFrom parent componentWithin component
UpdatesCause re-renderCause re-render

9. What are Controlled Components?

Answer: Controlled components have their form data handled by React state:

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

The React component controls what happens in the form on subsequent user input.

10. What are Uncontrolled Components?

Answer: Uncontrolled components store their own state internally using refs:

jsx
function Form() {
  const inputRef = useRef(null);
  
  const handleSubmit = (event) => {
    alert(inputRef.current.value);
    event.preventDefault();
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={inputRef} />
      <button type="submit">Submit</button>
    </form>
  );
}

11. What are React Fragments?

Answer: Fragments let you group elements without adding extra DOM nodes:

jsx
function List() {
  return (
    <>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </>
  );
}

Or using explicit syntax:

jsx
<React.Fragment key={item.id}>
  {/* content */}
</React.Fragment>

12. What is Conditional Rendering?

Answer: Different ways to render components conditionally:

jsx
// 1. if/else
function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

// 2. Ternary operator
function Message({ hasError }) {
  return (
    <div>
      {hasError ? <ErrorMsg /> : <SuccessMsg />}
    </div>
  );
}

// 3. Logical && operator
function Notification({ messages }) {
  return (
    <div>
      {messages.length > 0 && 
        <p>You have {messages.length} unread messages</p>
      }
    </div>
  );
}

13. What are Lists and Keys?

Answer: Keys help React identify which items have changed, been added, or removed:

jsx
function NumberList({ numbers }) {
  const listItems = numbers.map((number) =>
    <li key={number.id}>{number.value}</li>
  );
  return <ul>{listItems}</ul>;
}

Key rules:

  • Must be unique among siblings

  • Should be stable identifiers

  • Avoid using index as key unless list is static

14. What are React Hooks?

Answer: Hooks are functions that let you use React features in function components:

jsx
import { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  
  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);
  
  return <button onClick={() => setCount(count + 1)}>Click</button>;
}

15. What are the Rules of Hooks?

Answer:

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

  2. Only Call Hooks from React Functions: Call them from React function components or custom hooks

  3. Use ESLint Plugin: React provides eslint-plugin-react-hooks to enforce these rules


Hooks & State Management (Questions 16-30)

16. Explain the useState Hook

Answer: useState is a Hook that lets you add state to function components:

jsx
function Counter() {
  const [count, setCount] = useState(0);
  const [user, setUser] = useState({ name: 'John', age: 30 });
  
  // Functional updates for state based on previous state
  const increment = () => {
    setCount(prevCount => prevCount + 1);
  };
  
  // Updating objects
  const updateAge = () => {
    setUser(prevUser => ({
      ...prevUser,
      age: prevUser.age + 1
    }));
  };
}

17. Explain the useEffect Hook

Answer: useEffect handles side effects in function components:

jsx
useEffect(() => {
  // Side effect code here
  console.log('Component mounted or updated');
  
  // Cleanup function (optional)
  return () => {
    console.log('Component will unmount');
  };
}, [dependency1, dependency2]); // Dependency array

Dependency array behaviors:

  • []: Runs once after initial render (componentDidMount)

  • [dep]: Runs when dep changes (componentDidUpdate)

  • No array: Runs after every render

18. What are Custom Hooks?

Answer: Custom Hooks let you extract component logic into reusable functions:

jsx
// Custom Hook
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];
}

// Using the custom hook
function Component() {
  const [name, setName] = useLocalStorage('name', 'John');
  // ...
}

19. Explain the useContext Hook

Answer: useContext provides a way to pass data through the component tree without prop drilling:

jsx
// 1. Create Context
const ThemeContext = React.createContext('light');

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

// 3. Consume Context
function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div>Current theme: {theme}</div>;
}

20. Explain the useReducer Hook

Answer: useReducer is an alternative to useState for complex state logic:

jsx
const initialState = { count: 0 };

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

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'increment' })}>
        +
      </button>
    </>
  );
}

21. Explain the useRef Hook

Answer: useRef returns a mutable ref object that persists for the lifetime of the component:

jsx
function TextInput() {
  const inputRef = useRef(null);
  
  const focusInput = () => {
    inputRef.current.focus();
  };
  
  return (
    <>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}

22. Explain the useMemo Hook

Answer: useMemo memoizes expensive calculations:

jsx
function ExpensiveComponent({ list }) {
  const sortedList = useMemo(() => {
    console.log('Sorting...');
    return list.sort((a, b) => a - b);
  }, [list]); // Only re-sort when list changes
  
  return <div>{sortedList.join(', ')}</div>;
}

23. Explain the useCallback Hook

Answer: useCallback returns a memoized callback function:

jsx
function Parent() {
  const [count, setCount] = useState(0);
  
  const increment = useCallback(() => {
    setCount(c => c + 1);
  }, []); // Function identity stays the same
  
  return <Child onIncrement={increment} />;
}

const Child = React.memo(function Child({ onIncrement }) {
  console.log('Child rendered');
  return <button onClick={onIncrement}>Increment</button>;
});

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

Answer: Prop drilling is passing props through multiple intermediate components:

jsx
// Problem: Prop drilling
function App() {
  return <A user="John" />;
}
function A({ user }) {
  return <B user={user} />;
}
function B({ user }) {
  return <C user={user} />; // C needs user, but B doesn't
}

// Solutions:
// 1. Context API
// 2. Component composition
// 3. State management libraries

25. What is Lifting State Up?

Answer: Moving shared state to the closest common ancestor:

jsx
function Parent() {
  const [temperature, setTemperature] = useState('');
  
  return (
    <>
      <Celsius temp={temperature} onChange={setTemperature} />
      <Fahrenheit temp={temperature} onChange={setTemperature} />
    </>
  );
}

function Celsius({ temp, onChange }) {
  return (
    <input 
      value={temp} 
      onChange={e => onChange(e.target.value)} 
    />
  );
}

Performance & Optimization (Questions 26-35)

26. How to optimize React performance?

Answer:

  1. React.memo: Memoize functional components

  2. useMemo/useCallback: Memoize values/functions

  3. Code Splitting: Lazy load components

  4. Virtualization: For large lists (react-window)

  5. Avoid Inline Functions/Objects: In render methods

  6. Profiler API: Identify bottlenecks

27. What is React.memo?

Answer: React.memo is a higher-order component that memoizes functional components:

jsx
const MyComponent = React.memo(function MyComponent(props) {
  // Renders only when props change
  return <div>{props.value}</div>;
});

// Custom comparison function
const MyComponent = React.memo(
  function MyComponent(props) {
    return <div>{props.value}</div>;
  },
  (prevProps, nextProps) => {
    // Return true if props are equal (don't re-render)
    return prevProps.value === nextProps.value;
  }
);

28. What is Code Splitting?

Answer: Code splitting divides your bundle into smaller chunks:

jsx
import React, { Suspense, lazy } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
}

29. What are Error Boundaries?

Answer: Error boundaries catch JavaScript errors in child components:

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

// Usage
<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

30. What is Reconciliation?

Answer: Reconciliation is React's diffing algorithm that determines what needs to be updated in the DOM:

  1. Elements of different types: Tear down old tree, build new one

  2. DOM elements of same type: Update changed attributes only

  3. Component elements of same type: Update props, re-render

  4. Lists: Use keys to identify items


Advanced Concepts (Questions 36-51)

31. What are Higher-Order Components (HOCs)?

Answer: HOCs are functions that take a component and return a new component:

jsx
function withLogger(WrappedComponent) {
  return function(props) {
    console.log('Rendering:', WrappedComponent.name);
    return <WrappedComponent {...props} />;
  };
}

const EnhancedComponent = withLogger(MyComponent);

32. What are Render Props?

Answer: Render props is a pattern using a prop that returns a React element:

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

// Or using children prop
<Mouse>
  {mouse => (
    <p>Mouse position: {mouse.x}, {mouse.y}</p>
  )}
</Mouse>

33. What are Portals?

Answer: Portals render children into a DOM node outside parent hierarchy:

jsx
import ReactDOM from 'react-dom';

function Modal({ children }) {
  return ReactDOM.createPortal(
    children,
    document.getElementById('modal-root')
  );
}

34. What is React.StrictMode?

Answer: StrictMode is a tool for highlighting potential problems:

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

It helps with:

  • Identifying unsafe lifecycles

  • Warning about legacy string ref API

  • Detecting unexpected side effects

  • Detecting legacy context API

35. How does React handle events?

Answer: React events are synthetic events that wrap native browser events:

jsx
function Button() {
  const handleClick = (event) => {
    event.preventDefault();
    console.log('Clicked!');
    // Event pooling (older React): event.persist()
  };
  
  return <button onClick={handleClick}>Click me</button>;
}

36. What are React Server Components? (2026 Update)

Answer: Server Components run on the server and send minimal JavaScript to client:

jsx
// Server Component (can use server-only features)
async function Note({ id }) {
  const note = await db.notes.get(id); // Direct DB access
  return <NoteEditor note={note} />;
}

Benefits:

  • Zero bundle size for server components

  • Direct access to backend resources

  • Automatic code splitting

  • Improved performance

37. What is Concurrent Mode?

Answer: Concurrent Mode makes React apps more responsive by:

  • Interruptible rendering: Can pause, resume, or abandon renders

  • Automatic batching: Groups multiple state updates

  • Transitions: Distinguish urgent vs non-urgent updates

  • Suspense for Data Fetching: Declarative data loading

38. What is Suspense?

Answer: Suspense lets components "wait" for something before rendering:

jsx
<Suspense fallback={<Spinner />}>
  <ProfilePage />
</Suspense>

// With data fetching
const resource = fetchProfileData();

function ProfilePage() {
  return (
    <Suspense fallback={<h1>Loading profile...</h1>}>
      <ProfileDetails />
      <Suspense fallback={<h1>Loading posts...</h1>}>
        <ProfileTimeline />
      </Suspense>
    </Suspense>
  );
}

39. How to handle forms in React?

Answer:

jsx
// Controlled component approach
function Form() {
  const [formData, setFormData] = useState({
    name: '',
    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="name" value={formData.name} onChange={handleChange} />
      <input name="email" value={formData.email} onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  );
}

40. How to test React components?

Answer:

jsx
// Using Jest and React Testing Library
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';

test('button clicks', () => {
  const handleClick = jest.fn();
  render(<Button onClick={handleClick}>Click me</Button>);
  
  fireEvent.click(screen.getByText('Click me'));
  expect(handleClick).toHaveBeenCalledTimes(1);
});

41. What are React Lifecycle Methods?

Answer: For class components (mostly replaced by Hooks):

  1. Mounting: constructor(), static getDerivedStateFromProps(), render(), componentDidMount()

  2. Updating: static getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate(), componentDidUpdate()

  3. Unmounting: componentWillUnmount()

  4. Error Handling: static getDerivedStateFromError(), componentDidCatch()

42. What is the significance of keys?

Answer: Keys help React identify which items have changed:

  • Without keys: React re-creates entire list on changes

  • With keys: React reorders/moves existing items

  • Bad practice: Using array indices as keys (causes issues with reordering)

  • Best practice: Stable, unique IDs from data

43. How to make API calls in React?

Answer:

jsx
function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  
  useEffect(() => {
    const fetchUsers = async () => {
      setLoading(true);
      try {
        const response = await fetch('/api/users');
        const data = await response.json();
        setUsers(data);
      } catch (error) {
        console.error('Error:', error);
      } finally {
        setLoading(false);
      }
    };
    
    fetchUsers();
  }, []);
  
  if (loading) return <div>Loading...</div>;
  return <ul>{users.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
}

44. What are Pure Components?

Answer: PureComponent implements shouldComponentUpdate with shallow prop/state comparison:

jsx
class PureCounter extends React.PureComponent {
  render() {
    return <div>{this.props.count}</div>;
  }
}

Function component equivalent:

jsx
const PureCounter = React.memo(function PureCounter({ count }) {
  return <div>{count}</div>;
});

45. How to handle routing in React?

Answer: Using React Router v6:

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

function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/users/:id" element={<User />} />
      </Routes>
    </BrowserRouter>
  );
}

46. What is Redux and when to use it?

Answer: Redux is a state management library for complex applications:

jsx
// When to use Redux:
// - Large-scale applications
// - Complex state logic
// - Shared state across many components
// - Need for time-travel debugging
// - Predictable state updates

// Basic Redux concepts:
// - Store: Single source of truth
// - Actions: Plain objects describing changes
// - Reducers: Pure functions that update state
// - Middleware: Handle async operations

47. What are React Refs?

Answer: Refs provide access to DOM nodes or React elements:

jsx
class AutoFocusInput extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }
  
  componentDidMount() {
    this.inputRef.current.focus();
  }
  
  render() {
    return <input ref={this.inputRef} />;
  }
}

48. What is Context API?

Answer: Context provides a way to share values between components without prop drilling:

jsx
const UserContext = React.createContext();

function App() {
  const [user, setUser] = useState({ name: 'John' });
  
  return (
    <UserContext.Provider value={{ user, setUser }}>
      <Navbar />
      <MainContent />
    </UserContext.Provider>
  );
}

function Navbar() {
  const { user } = useContext(UserContext);
  return <nav>Welcome, {user.name}</nav>;
}

49. How does React handle styling?

Answer: Multiple approaches:

  1. Inline Styles: style={{ color: 'red', fontSize: 20 }}

  2. CSS Modules: import styles from './Button.module.css'

  3. Styled-components: CSS-in-JS library

  4. Tailwind CSS: Utility-first framework

  5. SASS/SCSS: Preprocessor integration

50. What are React Server Components vs Client Components?

Answer:

AspectServer ComponentsClient Components
Bundle SizeZero bundleFull bundle sent
Data FetchingDirect DB/API accessClient-side fetching
InteractivityNo event handlersFull interactivity
StateNo useState/useReducerFull state management
EffectsNo useEffectLifecycle effects

51. What are the latest React features in 2026?

Answer: Current trends and features:

  1. React Server Components: Production-ready

  2. Actions: Simplified form handling with async operations

  3. Enhanced Hooks: New hooks for common patterns

  4. Improved DevTools: Better debugging capabilities

  5. Automatic optimization: Compiler improvements

  6. WebAssembly integration: For performance-critical tasks


Conclusion & Best Practices

React Best Practices for 2026:

  1. Use Function Components and Hooks as primary approach

  2. Implement proper TypeScript for type safety

  3. Follow component composition over inheritance

  4. Keep components small and focused (Single Responsibility)

  5. Use meaningful naming conventions

  6. Implement proper error boundaries

  7. Optimize performance proactively

  8. Write comprehensive tests

  9. Use React's built-in features before adding libraries

  10. Stay updated with React ecosystem

Common Interview Tips:

  1. Understand fundamentals thoroughly

  2. Practice coding challenges with real React problems

  3. Explain your thought process during technical interviews

  4. Be familiar with both old and new patterns

  5. Discuss trade-offs between different approaches

  6. Show understanding of performance implications

  7. Demonstrate knowledge of React ecosystem

  8. Ask clarifying questions before solving problems

This comprehensive guide covers the essential knowledge needed for React interviews in 2026. Remember that React continues to evolve, so staying current with official documentation and community trends is crucial for success in both interviews and real-world development.

#career

Ready to Build Your Resume?

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

51 Top React JS Basic Interview Questions for Beginners (2026) | Hirecta Interview Prep | Hirecta