Uncategorized

Top 30 React Js questions and answers with example code

Introduction

React has become one of the most popular JavaScript libraries for building dynamic and interactive user interfaces. It provides developers with the tools to create fast and responsive web applications by breaking down the interface into reusable components. Understanding the fundamentals of React is crucial for any developer looking to master front-end development. This blog post aims to answer some of the most common questions about React, ranging from the basics of components and JSX to more advanced concepts like Redux, hooks, and React’s Concurrent Mode.

With 30 essential questions and their answers, we’ll walk through key concepts, including the Virtual DOM, React Router, Context API, and the differences between functional and class components. We will also explore advanced topics such as Redux, error boundaries, and performance optimization using hooks like useMemo, useCallback, and useEffect.

This guide is perfect for beginners who are just starting with React, as well as intermediate developers looking to brush up on their skills or gain a deeper understanding of React’s powerful features. Whether you’re building a small application or working on large-scale projects, having a strong grasp of these concepts will help you create efficient, maintainable, and scalable React applications.

1. What is React?

  • Answer: React is an open-source JavaScript library used for building user interfaces, primarily for single-page applications. It allows developers to create reusable UI components and manage the application state efficiently.

2. What are Components in React?

  • Answer: Components are the building blocks of a React application. They are JavaScript functions or classes that return UI elements, and they allow for the reuse of code and the maintenance of complex UIs.

Example:

// Functional Component Example
function Greeting() {
return <h1>Hello, World!</h1>;
}

export default Greeting;

3. What is JSX?

  • Answer: JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML elements and components in JavaScript. It makes it easier to describe the UI in React.

Example:

const element = <h1>Hello, World!</h1>;

4. What is the Virtual DOM?

  • Answer: The Virtual DOM is a lightweight copy of the actual DOM. React updates the Virtual DOM first, then compares it to the real DOM, and only updates the real DOM with the necessary changes, improving performance.

5. What are props in React?

  • Answer: Props (short for properties) are used to pass data from a parent component to a child component. Props are immutable, meaning the child component cannot modify them.

Example:

// Parent Component
function Parent() {
return <Child name="Alice" />;
}

// Child Component
function Child(props) {
return <h1>Hello, {props.name}!</h1>;
}

6. What is state in React?

  • Answer: State refers to data that can change within a component. It is mutable and allows React components to manage their own data and re-render based on changes in the state.

Example:

import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default Counter;

 

7. What are lifecycle methods in React?

  • Answer: Lifecycle methods are special methods in class components that get called at different stages of a component’s existence (e.g., mounting, updating, unmounting). Examples include componentDidMount, shouldComponentUpdate, and componentWillUnmount.

Example:

class MyComponent extends React.Component {
componentDidMount() {
console.log('Component mounted');
}

render() {
return <h1>Hello, Lifecycle!</h1>;
}
}

export default MyComponent;

8. What is a functional component?

  • Answer: A functional component is a simpler way to write components in React. It is a JavaScript function that accepts props and returns JSX.

Example:

function MyComponent() {
return <h1>Hello, Functional Component!</h1>;
}

export default MyComponent;

9. What is a class component?

  • Answer: A class component is a traditional way to write React components using ES6 class syntax. It has a render() method and can have lifecycle methods and state.

Example:

class MyComponent extends React.Component {
render() {
return <h1>Hello, Class Component!</h1>;
}
}

export default MyComponent;

10. What is React Router?

  • Answer: React Router is a library for handling routing in React applications. It allows you to create dynamic and single-page navigation between different views or components.

Example:

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

function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>
);
}

function Home() {
return <h1>Home Page</h1>;
}

function About() {
return <h1>About Page</h1>;
}

export default App;

11. What is Redux?

  • Answer: Redux is a predictable state container for JavaScript apps. It is used to manage the application state in a centralized store and allows components to interact with the state in a predictable way.

Example:

// Action
const increment = () => ({ type: 'INCREMENT' });

// Reducer
const counter = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
default:
return state;
}
};

// Store (with Redux)
import { createStore } from 'redux';
const store = createStore(counter);

12. What are hooks in React?

  • Answer: Hooks are functions that let you “hook into” React state and lifecycle features from functional components. Some common hooks include useState, useEffect, and useContext.

Example:

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

function MyComponent() {
const [count, setCount] = useState(0);

useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}

export default MyComponent;

13. What is the difference between useState and useReducer?

  • Answer: useState is used for managing simple state variables, while useReducer is typically used when the state is more complex or when the logic for updating the state is more involved, like handling multiple actions.

Example (useReducer):

import React, { useReducer } from 'react';

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:
return state;
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);

return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}

export default Counter;

14. What is useEffect?

  • Answer: useEffect is a hook that allows you to perform side effects in functional components, such as fetching data, setting up subscriptions, or manually changing the DOM.

Example:

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

function FetchData() {
const [data, setData] = useState(null);

useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty dependency array means this effect runs only once

return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}

export default FetchData;

 

15. What is Context API in React?

  • Answer: The Context API is a way to share values like themes, user data, or authentication status across components without passing props down manually at every level.

Example:

import React, { createContext, useContext, useState } from 'react';

const ThemeContext = createContext();

function App() {
const [theme, setTheme] = useState('light');

return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<MyComponent />
</ThemeContext.Provider>
);
}

function MyComponent() {
const { theme, setTheme } = useContext(ThemeContext);

return (
<div>
<p>Current Theme: {theme}</p>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
}

export default App;

16. What is the difference between controlled and uncontrolled components?

  • Answer: A controlled component is one whose value is controlled by React state, while an uncontrolled component manages its own state internally. Controlled components provide better control over the form data.

Example of Controlled Component:

function ControlledInput() {
const [value, setValue] = useState('');

const handleChange = (e) => {
setValue(e.target.value);
};

return <input value={value} onChange={handleChange} />;
}

export default ControlledInput;

Example of Uncontrolled Component:

function UncontrolledInput() {
const inputRef = useRef(null);

const handleSubmit = () => {
alert(inputRef.current.value);
};

return (
<div>
<input ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}

export default UncontrolledInput;

 


17. What is a higher-order component (HOC)?

  • Answer: A higher-order component (HOC) is a function that takes a component and returns a new component with additional props or behavior, enhancing the original component without modifying it directly.

Example:

function withLogging(WrappedComponent) {
return function (props) {
console.log('Component Rendered');
return <WrappedComponent {...props} />;
};
}

function MyComponent() {
return <h1>Hello, HOC!</h1>;
}

const EnhancedComponent = withLogging(MyComponent);

export default EnhancedComponent;

 

18. What is the use of key in React?

  • Answer: The key prop is used to uniquely identify elements in a list. React uses these keys to optimize the re-rendering process when elements are added, removed, or rearranged.

Example:

const items = ['Apple', 'Banana', 'Cherry'];

function ItemList() {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}

export default ItemList;

19. What is React.memo?

  • Answer: React.memo is a higher-order component that memoizes a component. It prevents unnecessary re-renders by comparing the previous props with the new ones. If the props haven’t changed, the component won’t re-render.

Example:

const MyComponent = React.memo(function MyComponent({ name }) {
console.log('Rendering...');
return <h1>{name}</h1>;
});

export default MyComponent;

20. What is a fragment in React?

  • Answer: A fragment is a way to group multiple elements without adding extra nodes to the DOM. It is useful when returning multiple elements from a component.

Example:

function MyComponent() {
return (
<>
<h1>Hello</h1>
<p>This is a fragment example</p>
</>
);
}

export default MyComponent;

21. What are error boundaries?

  • Answer: Error boundaries are React components that catch JavaScript errors anywhere in their child component tree and display a fallback UI instead of crashing the whole component tree.

Example:

export default ErrorBoundary;

22. What is useRef?

  • Answer: useRef is a hook that allows you to persist values across renders without causing re-renders. It is often used to reference DOM elements directly.

Example:

import React, { useRef } from 'react';

function FocusInput() {
const inputRef = useRef(null);

const handleFocus = () => {
inputRef.current.focus();
};

return (
<div>
<input ref={inputRef} />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}

export default FocusInput;

23. What are synthetic events in React?

  • Answer: Synthetic events are React’s cross-browser wrapper around the browser’s native event system. They normalize events so that they behave consistently across different browsers.

24. What is useCallback?

  • Answer: useCallback is a hook that returns a memoized version of a function, ensuring that the function does not get recreated on every render unless its dependencies change.

Example:

import React, { useState, useCallback } from 'react';

function Parent() {
const [count, setCount] = useState(0);

const increment = useCallback(() => {
setCount(count + 1);
}, [count]);

return (
<Child increment={increment} />
);
}

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

export default Parent;

25. What is useMemo?

  • Answer: useMemo is a hook that memoizes the result of a computation and returns the cached result unless the dependencies change, optimizing performance for expensive calculations.

Example:

import React, { useMemo, useState } from 'react';

function ExpensiveCalculation() {
const [count, setCount] = useState(0);

const expensiveValue = useMemo(() => {
return count * 2;
}, [count]);

return (
<div>
<p>Calculated Value: {expensiveValue}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default ExpensiveCalculation;

 

26. What are React DevTools?

  • Answer: React DevTools is a browser extension that allows developers to inspect the React component hierarchy, view the state and props of components, and debug React applications more effectively.

27. What is the use of React.StrictMode?

  • Answer: React.StrictMode is a wrapper component that helps identify potential problems in an application by running additional checks and warnings in development mode.

Example:

import React from 'react';

function App() {
return (
<React.StrictMode>
<MyComponent />
</React.StrictMode>
);
}

export default App;

 

28. What is a “Single Page Application” (SPA) in React?

  • Answer: A single-page application (SPA) is an application that loads a single HTML page and dynamically updates content as the user interacts with it, without refreshing the entire page.

29. What is code splitting in React?

  • Answer: Code splitting is the practice of breaking up large bundles of JavaScript into smaller, more manageable pieces, which can be loaded only when needed, improving app performance.

Example using React.lazy:

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

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

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

export default App;

30. What is React’s Concurrent Mode?

  • Answer: Concurrent Mode is a feature that helps React apps stay responsive and work seamlessly, even when rendering complex UI updates by allowing React to interrupt rendering work as needed.

(As of now, Concurrent Mode is experimental and not fully stable in production.)

Leave a Reply

Your email address will not be published. Required fields are marked *