React JS Interview Questions & Answers with Examples
What is React?
React is a popular JavaScript library for building user interfaces. It was created by Facebook and is now maintained by a large community of developers. React allows developers to create complex UI components and manage state in a more efficient way. It is often used in conjunction with other popular tools and libraries such as Redux, Webpack, and Babel.
What is JSX?
JSX is a syntax extension for JavaScript that allows developers to write HTML-like syntax in their JavaScript code. It is often used with React to define the structure and appearance of UI components. JSX code is compiled into regular JavaScript by tools like Babel, which allows it to be executed in any browser.
What is a component in React?
In React, a component is a modular, reusable piece of code that defines a part of a user interface. Components can be thought of as building blocks for larger applications. They are typically composed of HTML-like markup (in the form of JSX) and JavaScript logic that defines their behavior.
How do you create a component in React?
To create a component in React, you first need to define a JavaScript function that returns some JSX code. Here’s an example of a simple component that displays a message:
import React from 'react';
function Message() {
return (
<div>
<h1>Hello, world!</h1>
<p>This is a message from a React component.</p>
</div>
);
}
Once you have defined your component, you can use it in other parts of your application by simply importing it and including it in your JSX code.
For example, you could include the Message
component in another component like this:
import React from 'react';
import Message from './Message';
function App() {
return (
<div>
<h1>Welcome to my app</h1>
<Message />
</div>
);
}
In this example, the App
component includes the Message
component by simply including it in its JSX code. When the App
component is rendered, the Message
component will also be rendered and its output will be included in the final output of the App
component.
300 React JS Interview Questions and Answers for 2023 | Quiz
What is the difference between a functional and class component?
In React, there are two main types of components: functional components and class components.
Functional components are defined as JavaScript functions that return some JSX code. They are simple, lightweight, and typically used for simple UI components that don’t require any state or lifecycle methods. They can be easily reused and composed to create more complex components.
Here’s an example of a functional component:
import React from 'react';
function Hello(props) {
return <h1>Hello, {props.name}!</h1>;
}
Class components, on the other hand, are defined as ES6 classes that extend the React.Component
class. They have more features than functional components, including the ability to manage state and lifecycle methods. They are typically used for more complex UI components that require more logic and interaction. Here's an example of a class component:
import React from 'react';
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.handleClick()}>Increment</button>
</div>
);
}
}
What is the virtual DOM in React?
The virtual DOM (or virtual Document Object Model) is a concept in React that represents the entire HTML document as a JavaScript object. It is an in-memory representation of the actual DOM, which allows React to make changes to the UI more efficiently.
When a component’s state changes, React updates the virtual DOM with the new UI state. It then compares the virtual DOM with the actual DOM to determine what has changed, and updates only the parts of the actual DOM that need to be updated. This process is much faster than updating the entire DOM, which is why React is able to provide a fast and efficient user experience.
What is state in React?
In React, state is an object that represents the internal state of a component. It is used to manage data that can change over time, such as user input or server responses. When the state of a component changes, React automatically re-renders the component and updates the UI.
State can only be managed by class components, not functional components. It is typically initialized in the constructor
method and updated using the setState
method. Here's an example of a component with state:
import React from 'react';
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.handleClick()}>Increment</button>
</div>
);
}
}
What is the difference between state and props in React?
State and props are two concepts in React that are often used interchangeably, but they are actually different.
State is internal to a component and can be changed by the component itself using the setState
method. It is used to manage data that can change over time, such as user input or server responses.
Props, on the other hand, are passed down to a component from its parent component. They are read-only and cannot be changed by the component itself. They are used to pass data and functionality between components.
How do you pass data from a parent component to a child component in React?
In React, data can be passed from a parent component to a child component using props.
Here’s an example:
// Parent component
import React from 'react';
import Child from './Child';
function Parent() {
const message = 'Hello from Parent!';
return (
<div>
<Child message={message} />
</div>
);
}
// Child component
import React from 'react';
function Child(props) {
return <h1>{props.message}</h1>;
}
In this example, the parent component (Parent
) passes a message
prop to the child component (Child
) using the syntax message={message}
. The child component then receives the prop in its props
object and renders it using props.message
.
What is the significance of the ‘key’ prop in React?
The key
prop is a special attribute in React that is used to identify unique components in a list. When rendering a list of components, React uses the key
prop to determine which components have changed and need to be updated.
Each component in a list must have a unique key
prop. If two components in a list have the same key
, React will generate a warning and may not render the components correctly.
Here’s an example of using the key
prop in a list:
import React from 'react';
function MyList() {
const items = ['item1', 'item2', 'item3'];
return (
<ul>
{items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);
}
In this example, the key
prop is set to the value of each item in the items
array. This ensures that each list item has a unique key and allows React to efficiently update the list when it changes.
What is the purpose of the ‘ref’ attribute in React?
The ref
attribute is used in React to get a reference to a specific element or component in the DOM. It allows you to access the underlying DOM node or component instance and interact with it directly.
Here’s an example of using the ref
attribute to get a reference to an input element and focus it:
import React, { useRef } from 'react';
function MyForm() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus input</button>
</div>
);
}
In this example, the inputRef
object is created using the useRef
hook. The ref
attribute is then set to this object on the input
element. When the handleClick
function is called, it uses the focus
method to focus the input element.
The ref
attribute can also be used to get a reference to a child component instance, but this is generally discouraged in favor of using props and state to communicate between components.
What is the ‘useEffect’ hook in React and when would you use it?
The useEffect
hook is used in React to perform side effects such as fetching data, updating the document title, or adding event listeners. It allows you to run a function after rendering a component, and optionally specify dependencies that should trigger a re-run of the function.
Here’s an example of using the useEffect
hook to fetch data from an API:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function MyComponent() {
const [data, setData] = useState([]);
useEffect(() => {
async function fetchData() {
const response = await axios.get('https://example.com/api/data');
setData(response.data);
}
fetchData();
}, []);
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
In this example, the useEffect
hook is used to fetch data from an API and set it to the data
state. The empty array passed as the second argument to useEffect
indicates that the effect should only run once, when the component is mounted.
What is the ‘useState’ hook in React and when would you use it?
The useState
hook is used in React to add state to functional components. It allows you to declare state variables and update them using the useState
function.
Here’s an example of using the useState
hook to add state to a component:
import React, { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
In this example, the useState
hook is used to declare a count
state variable and an setCount
function to update it. The handleClick
function uses setCount
to increment the count
state by 1 when the button is clicked.
What is the ‘useReducer’ hook in React and when would you use it?
The useReducer
hook is used in React to manage complex state that involves multiple actions and transitions. It is similar to the useState
hook, but allows you to specify a reducer function that handles state transitions instead of using individual state update functions.
Here’s an example of using the useReducer
hook to manage a simple counter:
import React, { useReducer } from 'react';
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 MyComponent() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
function handleIncrement() {
dispatch({ type: 'increment' });
}
function handleDecrement() {
dispatch({ type: 'decrement' });
}
return (
<div>
<p>Count: {state.count}</p>
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleDecrement}>Decrement</button>
</div>
);
}
In this example, the useReducer
hook is used to manage a count
state variable
What is the ‘useCallback’ hook in React and when would you use it?
The useCallback
hook is used in React to memoize functions, which means that the function is only re-created if its dependencies change. It can be useful for optimizing performance by preventing unnecessary re-renders of components that use the memoized function as a prop.
Here’s an example of using the useCallback
hook to memoize a function:
import React, { useState, useCallback } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
In this example, the useCallback
hook is used to memoize the handleClick
function, which increments the count
state by 1. The useCallback
hook specifies the count
state as a dependency, so the function is re-created when the count
state changes.
What is the ‘useMemo’ hook in React and when would you use it?
The useMemo
hook is used in React to memoize values, which means that the value is only re-calculated if its dependencies change. It can be useful for optimizing performance by preventing unnecessary re-renders of components that use the memoized value.
Here’s an example of using the useMemo
hook to memoize a value:
import React, { useState, useMemo } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
const square = useMemo(() => {
return count * count;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<p>Square: {square}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
In this example, the useMemo
hook is used to memoize the square
value, which is the square of the count
state. The useMemo
hook specifies the count
state as a dependency, so the value is re-calculated when the count
state changes.
What is the ‘useRef’ hook in React and when would you use it?
The useRef
hook is used in React to create a mutable ref object that persists for the lifetime of the component. It can be useful for storing a value that needs to persist across renders, or for accessing the DOM node of a component.
Here’s an example of using the useRef
hook to store a value:
import React, { useState, useRef } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
const previousCount = useRef(0);
function handleClick() {
previousCount.current = count;
setCount(count + 1);
}
return (
<div>
<p>Count: {count}</p>
<p>Previous Count: {previousCount.current}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
In this example, the useRef
hook is used to create a previousCount
ref object that persists for the lifetime of the component.
What is the difference between the ‘useEffect’ and ‘useLayoutEffect’ hooks in React?
Both useEffect
and useLayoutEffect
are hooks in React that allow you to perform side effects in your components. The difference between them is when they are executed in relation to the component rendering.
useEffect
is executed after the component is rendered, while useLayoutEffect
is executed before the component is rendered. This means that useLayoutEffect
allows you to perform side effects that require access to the DOM before the browser paints the screen, which can result in a more responsive user interface.
Here’s an example of using the useEffect
hook:
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
In this example, the useEffect
hook is used to update the document title with the current count
state after the component is rendered.
Here’s an example of using the useLayoutEffect
hook:
import React, { useState, useLayoutEffect } from 'react';
function MyComponent() {
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
const handleResize = () => {
setWidth(window.innerWidth);
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return (
<div>
<p>Width: {width}px</p>
</div>
);
}
In this example, the useLayoutEffect
hook is used to add and remove an event listener for the window resize event before the component is rendered. The width
state is updated with the current inner width of the window.
What is the ‘forwardRef’ function in React and when would you use it?
The forwardRef
function is a built-in utility in React that allows you to forward a ref to a child component. It can be useful for creating reusable components that need to access the underlying DOM node or React component instance of a child component.
Here’s an example of using the forwardRef
function:
import React, { forwardRef } from 'react';
const MyInput = forwardRef((props, ref) => {
return (
<input type="text" {...props} ref={ref} />
);
});
function MyComponent() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<div>
<MyInput ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
In this example, the forwardRef
function is used to forward the ref
passed to the MyInput
component to the underlying input
element. The inputRef
ref is used to focus the input element when the Focus Input
button is clicked.
What is the ‘React Router’ and how would you use it?
React Router is a popular library for implementing client-side routing in React applications. It allows you to define routes and their corresponding components, enabling users to navigate to different pages within the application without the need to reload the entire page.
To use React Router, you would first need to install it using npm or yarn. Then, you can import it into your application and use the different components provided by the library, such as BrowserRouter
, Route
, and Link
.
The BrowserRouter
component wraps your entire application and enables routing functionality. The Route
component is used to define the different paths in your application and the components that should be rendered when the user navigates to those paths. Finally, the Link
component is used to create links to different paths in your application.
What is ‘Redux’ and how would you use it with React?
Redux is a state management library for JavaScript applications. It provides a centralized store that holds the application’s state and enables easy management of state changes through actions and reducers.
To use Redux with React, you would first need to install it using npm or yarn. Then, you can create a Redux store and wrap your application with the Provider
component provided by the library. This makes the store available to all components in your application.
To interact with the Redux store, you can use the useSelector
hook to access state values and the useDispatch
hook to dispatch actions that trigger state changes. You would also need to define reducers that handle the different types of actions that can occur in your application.
What is the ‘Redux Thunk’ middleware in Redux and how would you use it?
Redux Thunk is a middleware for Redux that enables the use of asynchronous actions. It allows you to dispatch functions as actions, which can then perform asynchronous operations before dispatching the actual action to update the state.
To use Redux Thunk, you would first need to install it using npm or yarn. Then, you can apply it to your Redux store using the applyMiddleware
function provided by the library. You would also need to define thunks, which are functions that return a function that dispatches the actual action.
In practice, you would use Redux Thunk when you need to perform asynchronous operations such as API calls or database queries before updating the state in your application.
What is ‘Redux Saga’ and how would you use it?
Redux Saga is another middleware for Redux that enables the use of asynchronous actions. It allows you to write complex asynchronous logic as a series of generator functions, making it easy to manage side effects in your application.
To use Redux Saga, you would first need to install it using npm or yarn. Then, you can define sagas, which are generator functions that listen for specific actions and perform side effects before dispatching new actions to update the state.
In practice, you would use Redux Saga when you need to manage complex asynchronous logic such as long-running processes, web sockets, or multiple API calls. It provides a powerful toolset for managing side effects in your application and can help make your code more maintainable and scalable.
What is ‘Immutable.js’ and how would you use it with React?
Immutable.js is a library that provides a collection of immutable data structures such as List, Map, and Set. In React, you can use Immutable.js to manage the state of your application more efficiently. With Immutable.js, you can make sure that your data is always kept in a consistent state, which can help avoid bugs and make your application more predictable.
For example, you can use an Immutable.js List to store an array of data that cannot be modified directly. Instead, you can create a new List with updated values whenever you need to update the data. This ensures that the original data remains unchanged, which can help prevent unexpected behavior in your application.
What is ‘React Native’ and how is it different from React?
React Native is a framework for building native mobile applications using React. While React is used to build web applications, React Native is used to build native mobile applications for iOS and Android. React Native allows you to write code in JavaScript and compile it to native code for the target platform, which can make it easier to build and maintain mobile applications.
One of the key differences between React and React Native is the way they handle rendering. React uses the browser’s DOM to render components, while React Native uses native components to render components on mobile devices. This means that React Native components have a different set of props and styling options than React components.
What are ‘Higher-Order Components’ (HOC) and when would you use them in React?
Higher-Order Components (HOC) are functions that take a component and return a new component with additional functionality. HOCs allow you to reuse code and logic across different components in your application. You can use HOCs to add functionality such as authentication, data fetching, or error handling to your components.
For example, you could create an HOC that adds authentication to a component by checking if the user is logged in before rendering the component. This allows you to reuse this authentication logic across multiple components in your application.
What is ‘Render Prop’ and when would you use it in React?
Render Prop is a pattern in React where a component takes a function as a prop and calls it to render its content. The function takes the component’s state and returns the JSX to render. This allows you to share state and logic between components without using Higher-Order Components.
Render Prop can be used to create reusable components that can be customized with different content or functionality. For example, you could create a component that renders a dropdown menu and takes a function to render the menu items. This allows you to reuse the dropdown component with different menu items in different parts of your application.