ReactHooks
What is React Hooks?
React Hooks is a function that lets us use state and other React
features without writing a class. They were introduced in React
16.8 to enable functional components to use state which means
to make the code good and easy to understand.
React hooks are functions that enable functional components to
use state and lifecycle features that were previously only
available in class components. Hooks provide functions
like useState, useEffect, useContext, etc., that allow we to
"hook into" React features from functional components .
2. What problems do React Hooks solve?
React Hooks solves the problems of sharing the stateful logic
between components in a more modular and reusable way than
class components.
3. What are the basic built-in React Hooks?
The basic built-in React Hooks are useState, useEffect,
useContext, useReducer, useCallback, useMomo,
useRef and useImperativeHandle.
useState enables components to manage and update
their own state without using classes.
useEffect is used to connect components to an external
system.
useContext it is used to consume data from a Context
in a functional component.
useReducer is used to manage complex state logic
through a reducer function.
useCallback used to memoize functions, preventing
unnecessary re-renders in child components.
useMemo is used to memoize the result of a function
computation, preventing unnecessary recalculations.
useRef is used to create mutable references that persist
across renders in functional components.
useImperativeHandler customizes the instance value that
is exposed when using ref with functional components.
4. How does useState work?
The useState Hook enables we to add state to wer functional
components. It returns a stateful value and a function that can
be used to update that value. By using Hooks, we can extract
stateful logic from wer component, which can then be tested
independently.
5. When would we use useEffect?
useEffect is typically used in React functional components to
perform side effects, like data fetching, subscriptions,
or DOM manipulations, after the component has rendered. It's
similar to lifecycle methods in class components, but it's more
flexible and concise.
6. What is the purpose of useCallback Hooks?
The purpose of useCallback Hooks is used to memoize functions,
and prevent unnecessary re-rendering of child components that
rely on those components. The useCallback function in React is
mainly used to keep a reference to a function constant across
multiple re-renders. This feature becomes useful when we want
to prevent the unnecessary re-creation of functions, especially
when we need to pass them as dependencies to other hooks
such as useMemo or useEffect.
7. Explain the difference between useMemo and
useCallback?
Here's a difference of useMemo and useCallback int tabular
form:
useMemo useCallback
Memoizes a value (result of a
Memoizes a function
function)
Memoized value Memoized function reference
When we need to memoize a When we need to memoize a
calculated value function
Recalculates when any Recreates the function only when
dependency changes any dependency changes
Example: Memoizing event
Example: Memoizing the result
handler functions to prevent re-
of expensive computations
renders
8. What is the useContext used for?
useContext is a function that enables access to context values
provided by a Context.Provider component at a higher level in
the component tree. This allows data to be passed down the tree
without the need to manually pass props at each level.
9. How does useReducer differ from useState?
useState useReducer
Handles state with a single Handles state with more complex
value logic and multiple values
Simple to use, suitable for More complex, suitable for managing
basic state needs complex state logic
Simple state updates, like Managing state with complex
toggles or counters transitions and logic
Directly updates state with Updates state based on dispatched
a new value actions and logic
Requires a reducer function to
Not used
determine state changes
Logic is dispersed where Logic is centralized within the
state is used reducer function
10. What is useEffect Hooks?
The useEffect Hooks is used to connect component to an
external system. In this the depenedeny array specifies when the
effect should run based on changes in its dependencies and
when the dependency array is absent in useEffect, the effect will
run after every render.
When we provide dependencies in the dependency array
of useEffect, the effect will run:
Initially after the first render.
Whenever any of the dependencies change between
renders.
If the dependencies are an empty array ( [] ), the effect
will only run once after the initial render, similar
to componentDidMount in class components.
11. When would we use useRef?
The useRef is used in React functional components when we need
to keep a mutable value around across renders without
triggering a re-render. It's commonly used for accessing DOM
elements, caching values, or storing mutable variables. we can
use useRef to manage focus within wer components, such as
focusing on a specific input element when a condition is met
without triggering re-renders.
12. Explain the purpose of useLawetEffect?
The useLawetEffect is similar to useEffect but fires
synchronously after all DOM mutations. It's useful for reading
from the DOM or performing animations before the browser
paints. Due to its synchronous nature, excessive usage
of useLawetEffect may potentially impact performance,
especially if the logic within it is computationally intensive or
blocking. It's essential to use useLawetEffect judiciously and
consider performance implications carefully.
13. What is Custom Hooks?
Custom hooks in React are like wer own personal tools that we
can create to make building components easier. They're
functions we write to do specific tasks, and then we can reuse
them in different components. They're handy because they let
we keep wer code organized and share logic between different
parts of wer application without repeating werself.
14. How do we create a custom Hook?
Here is to creating a custom Hooks step-by-step.
Create a function : Start by defining a
regular JavaScript function. It can have any name, but it's
a convention to prefix it with "use" to indicate that it's a
hook.
Write the logic : Inside wer custom hook function, write
the logic we want to encapsulate and reuse. we can use
existing hooks like useState , useEffect , or other custom
hooks if needed.
Return values : Ensure wer custom hook returns
whatever values or functions we want to expose to
components that use it.
Use the hook : we can now use wer custom hook in any
functional component by calling it. React will recognize it
as a hook because it starts with "use".
15. What is the benefit of using custom Hooks?
The benefits of using custom hooks in React include code
reusability, separation of concerns, abstraction of
complex logic, improved testability, and the ability to
compose hooks together for flexible and scalable code. They
help in maintaining a clear separation between presentation and
business logic, making it easier to reason about and maintain
wer codebase as it grows.
16. Can custom Hooks accept parameters?
Yes, custom hooks in React can indeed accept parameters. By
accepting parameters, custom hooks become more flexible and
can adapt their behavior based on the specific needs of different
components.
import { useEffect } from 'react';
function useDocumentTitle(title) {
useEffect(() => {
document.title = title;
}, [title]);
}
// Usage:
function MyComponent() {
useDocumentTitle('Hello GfG!');
return <div>GeeksforGeeks content...</div>;
}
17. How do we share code between custom Hooks?
To share code between custom hooks in React , we can simply
create regular JavaScript functions or utility functions and import
them into wer custom hooks as needed. These shared functions
can encapsulate common logic or helper functions that are used
across multiple custom hooks.
18. What are the rules of Hooks?
The rules of Hooks are:
Only Call Hooks at the Top Level : Don't call Hooks
inside loops, conditions, or nested functions. Always use
Hooks at the top level of wer functional components or
other custom Hooks.
Only Call Hooks from React Functions : Ensure that
we only call Hooks from within React functional
components or custom Hooks. Don't call Hooks from
regular JavaScript functions.
19. How do we conditionally run effects with
useEffect?
To conditionally run effects with useEffect in React, we can use
the dependency array as the second argument to specify the
values that the effect depends on. By updating these
dependencies, we can control when the effect should run.
import React, {
useEffect,
useState
}
from 'react';
import { fetchData }
from './actions/actions';
function App({ condition }) {
const [data, setData] = useState(null);
useEffect(() => {
if (condition) {
fetchData().then(result =>
setData(result));
}
}, [condition]);
return (
<div>
{data ? (
<p>
Data available: {data}
</p>
) : (
<p>No data available</p>
)}
</div>
);
}
export default App;
20. What happens if we omit dependencies in the
dependency array of useEffect?
If we omit dependencies in the dependency array of useEffect,
the effect will run after every render. This means that the effect
will be executed on the initial render and after every subsequent
re-render, regardless of whether any specific values have
changed.
import React, {
useEffect,
useState
}
from 'react';
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("See the Effect here");
});
return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default App;
21. How do we fetch data with useEffect?
we can fetch data with useEffect in React by performing the
data fetching operation inside the effect function. Typically, we
use asynchronous functions like fetch to make HTTP requests to
an API endpoint and update the component state with the
fetched data.
import React,
{
useEffect,
useState
}
from 'react';
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("See the Effect here");
});
return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default App;
22. What is the purpose of the second argument in
useState?
The purpose of the second argument in useState is to initialize the
state value. When we call useState(initialValue),
the initialValue provided as the second argument is used to
initialize the state variable.
const [count, setCount] = useState(0);
In this '0' is the initial value provided as the second argument
to useState, so count will be initialized with ' 0' as its initial value.
23. Explain the concept of lazy initialization with
useState?
Lazy initialization with useState allows we to initialize state lazily
based on a function, which is only called on the initial render.
The concept of lazy initialization with useState in React allows we
to initialize state lazily, i.e., on-demand when it's needed, rather
than eagerly during component initialization. This means that we
can compute the initial state dynamically based on some
conditions or heavy computations.
24. What are the benefits of using React.memo?
React.memo is a higher-order component provided by React that
can be used to optimize functional components by memoizing
them. The benefits of using React.memo include improved
performance by memoizing component renders based on props,
reduced re-renders, enhanced component reusability, and
simplified optimization without manual memoization logic.
25. How do we test components that use Hooks?
We can test components that use hooks in React using testing
libraries like@testing-library/react or enzyme. Write test cases to
simulate component rendering, user interactions, and expected
outcomes. Use testing utilities like render, fireEvent, and expect to
interact with components and assert their behavior, ensuring
hooks are working correctly.
26. Can we use Hooks in class components?
No, we cannot use hooks in class components directly. Hooks are
a feature introduced in React 16.8 to allow stateful logic to be
used in functional components. They cannot be used in class
components because hooks rely on the functional component's
call order to manage state and lifecycle behaviors, which is not
compatible with the class component's lifecycle methods.
27. How do we handle forms with Hooks?
we can handle forms with hooks in React by using
the useState hook to manage form state, and the onChange event
handler to update the state as the user interacts with the form
inputs. Additionally, we can use the handleSubmit function to
handle form submission and perform any necessary actions, such
as sending data to a server or updating the UI based on form
input.
28. What is the purpose of the useImperativeHandle
Hook?
The useImperativeHandle hook in React allows we to customize
the instance value that is exposed when using ref with functional
components. It's typically used to expose specific methods or
properties from a child component's instance to its parent
component.
29. How do we share state logic between
components?
We can share state logic between components in React using
techniques such as prop drilling, lifting state up, or by using
state management libraries like Redux or React Context.
Prop Drilling : Pass state and functions down through
props from parent to child components. This is suitable
for simple applications with a shallow component tree.
Lifting State Up : Move shared state and related
functions to the nearest common ancestor component
and pass them down as props to child components. This
is effective for managing state across multiple related
components.
State Management Libraries : Use state management
libraries like Redux or React Context for managing global
state that needs to be accessed by multiple components
across the application. These libraries provide centralized
state management and make it easier to share state
logic across components.
30. What are some common patterns for using
custom Hooks?
Some common patterns for using custom hooks in React are:
State Management : Custom hooks can encapsulate
stateful logic, making it reusable across components.
Side Effects : Custom hooks can handle side effects
such as data fetching, subscriptions, or imperative DOM
manipulations.
Abstraction of Complex Logic : Custom hooks can
abstract complex logic into reusable functions, improving
code readability and maintainability.
Composition : Custom hooks can be composed together
to create more complex behavior.
Integration with Third-party Libraries : Custom
hooks can integrate with third-party libraries or APIs,
providing a clean and reusable interface.
1. What is ReactJS?
ReactJS is a JavaScript library used to build reusable components
for the view layer in MVC architecture. It is used to build the
Single Page Application (SPA) due to its component-based
architecture, efficient re-rendering with the Virtual DOM, and
ability to manage dynamic content without needing full page
reloads. It is written in JSX.
Important Features of React:
Virtual DOM: React uses a virtual DOM to efficiently
update and render components, ensuring fast
performance by minimizing direct DOM manipulations.
Component-Based Architecture: React builds UI using
reusable, isolated components, making code more
modular, maintainable, and scalable.
Hooks: React Hooks allow functional components to
manage state and side effects, making them powerful
and more flexible.
Server-Side Rendering (SSR): React can be used for
server-side rendering, where HTML content is generated
on the server and sent to the client. This improves the
app’s performance, especially for SEO.
React Router: React Router enables navigation in a
React application. It allows you to define different routes
for different views in a single-page application (SPA).
2. Explain the MVC architecture.
The Model-View-Controller (MVC) framework is an
architectural/design pattern that separates an application into
three main logical components: Model, View, and Controller.
Each architectural component is built to handle specific
development aspects of an application. It isolates the business,
logic, and presentation layers from each other
3. Explain the building blocks of React.
The five main building blocks of React are
Components: These are reusable blocks of code that
return HTML.
JSX: It stands for JavaScript and XML and allows you to
write HTML in React.
Props and State: props are like function parameters
and State is similar to variables.
Context: This allows data to be passed through
components as props in a hierarchy.
Virtual DOM: It is a lightweight copy of the actual DOM
which makes DOM manipulation easier.
4. Explain props and state in React with differences
Props are used to pass data from one component to another. The
state is local data storage that is local to the component only
and cannot be passed to other components.
Here is the difference table of props and state In react
PROPS STATE
The Data is passed from
The Data is passed within the
one component to
component only.
another.
It is Immutable (cannot be
It is Mutable ( can be modified).
modified).
Props can be used with The state can be used only with the
state and functional state components/class component
components. (Before 16.0).
Props are read-only. The state is both read and write.
5. What is virtual DOM in React?
The Virtual DOM in React is an in-memory representation of the
actual DOM. It helps React efficiently update and render the user
interface by comparing the current and previous virtual DOM
states using a process called diffing.
How Virtual DOM Works
Efficient Rendering: The Virtual DOM is an in-memory
representation of the actual DOM that React uses to
optimize the process of updating and rendering UI
changes.
Diffing Algorithm: React compares the current and
previous versions of the Virtual DOM using a diffing
algorithm, identifying the minimal set of changes
required to update the real DOM.
Batch Updates: Instead of updating the real DOM
immediately, React batches multiple changes to reduce
unnecessary re-renders, improving performance.
Faster Updates: Since updating the real DOM is slow,
React minimizes direct DOM manipulations by only
making updates where necessary after comparing the
Virtual DOM.
Declarative UI: With the Virtual DOM, React allows
developers to write code in a declarative style, letting
React handle when and how to efficiently update the UI.
6. What is JSX?
JSX is basically a syntax extension of regular JavaScript and is
used to create React elements. These elements are then
rendered to the React DOM. All the React components are
written in JSX. To embed any JavaScript expression in a piece of
code written in JSX we will have to wrap that expression in curly
braces {}.
Example of JSX: The name written in curly braces { } signifies
JSX
const name = "Learner";
const element = (
<h1>
Hello,
{name}.Welcome to GeeksforGeeks.
</h1>
);
7. What are components and their type in React?
A Component is one of the core building blocks of React. In other
words, we can say that every application you will develop in
React will be made up of pieces called components. Components
make the task of building UIs much easier.
In React, we mainly have two types of components:
Functional Components: Functional components are
simply JavaScript functions. We can create a functional
component in React by writing a JavaScript function.
Class Components: The class components are a little
more complex than the functional components. The
functional components are not aware of the other
components in your program whereas the class
components can work with each other. We can pass data
from one class component to another class component.
8. How do browsers read JSX?
In general, browsers are not capable of reading JSX and only can
read pure JavaScript. The web browsers read JSX with the help of
a transpiler. Transpilers are used to convert JSX into JavaScript.
The transpiler used is called Babel.
9. Explain the steps to create a react application
and print Hello World?
To install React, first, make sure Node is installed on your
computer. After installing Node. Open the terminal and type the
following command.
npx create-react-app <<Application_Name>>
Navigate to the folder.
cd <<Application_Name>>
This is the first code of ReactJS Hello World!
import React from "react";
import "./App.css";
function App() {
return <div className="App">Hello World !</div>;
}
export default App;
Output:
Type the following command to run the application
npm start
React app
10. How to create an event in React?
To create an event in React, attach an event handler like onClick,
onChange, etc., to a JSX element. Define the handler function to
specify the action when the event is triggered, such as updating
state or executing logic.
function Component() {
doSomething(e);
{
e.preventDefault();
// Some more response to the event
}
return <button onEvent={doSomething}></button>;
}
11. Explain the creation of a List in React?
Lists are very useful when it comes to developing the UI of any
website. Lists are mainly used for displaying menus on a website.
To create a list in React use the map method of array as follows.
import React from "react";
import ReactDOM from "react-dom/client"; // Import react-dom/client
const numbers = [1, 2, 3, 4, 5];
const updatedNums = numbers.map((number) => {
return <li key={number}>{number}</li>; // Add a unique "key" prop
});
const root = ReactDOM.createRoot(document.getElementById("root")); //
Create the root
root.render(<ul>{updatedNums}</ul>); // Render the list into the root
element
Output:
List
12. What is a key in React?
A key is a special string attribute you need to include when
creating lists of elements in React. Keys are used in React to
identify which items in the list are changed, updated, or deleted.
In other words, we can say that keys are used to give an identity
to the elements in the lists.
13. How to write a comment in React?
There are two ways to write comments in React.
Multi-line comment: We can write multi-line comments
in React using the asterisk format /* */.
/*
This is a multi-line comment.
It can span multiple lines.
*/
Single line comment: We can write single comments in
React using the double forward slash //.
// This is a single-line comment
14. Explain the difference between React and
Angular?
Features React Angular
Angular is a
React is a JavaScript library.
framework. Angular
As it indicates react js
updates the Real DOM
updates only the virtual DOM
and the data flow is
is present and the data flow
ensured in the
is always in a single
Used as architecture in both
direction.
directions.
The architecture is
React is more simplified as it complex as it follows
Architect follows MVC ie., Model View MVVM models ie.,
ure Control. Model View-
ViewModel.
Features React Angular
Scalabilit It is less scalable than
It is highly scalable.
y React JS.
It supports Bi-
It supports Uni-directional
directional data
data binding which is one-
Data binding which is two
way data binding.
Binding way data binding.
DOM It has a virtual DOM. It has regular DOM.
15. Explain the use of render method in React?
React renders HTML to the web page by using a function called
render(). The purpose of the function is to display the specified
HTML code inside the specified HTML element. In the render()
method, we can read props and state and return our JSX code to
the root component of our app.
16. What is state in React?
The state is an instance of React Component Class that can be
defined as an object of a set of observable properties that
control the behaviour of the component. In other words, the
State of a component is an object that holds some information
that may change over the lifetime of the component.
17. Explain props in React?
React allows us to pass information to a Component using
something called props (which stands for properties). Props are
objects which can be used inside a component
We can access any props inside from the component’s class to
which the props is passed. The props can be accessed as shown
below:
this.props.propName;
18. What is higher-order component in React?
Higher-order components or HOC is the advanced method of
reusing the component functionality logic. It simply takes the
original component and returns the enhanced component. HOC
are beneficial as they are easy to code and read. Also, helps to
get rid of copying the same logic in every component.
19. Explain the difference between functional and
class component in React?
Functional
Components
Class Components
Features
A class component
A functional component is
requires you to extend
just a plain JavaScript
Definition from React. Component
pure function that accepts
and create a render
props as an argument
function
It must have the
Rendering No render method used render() method
returning JSX
Stateless or Also known as Stateless Also known as Stateful
Stateful components components
React lifecycle methods React lifecycle methods
(for example, can be used inside class
Lifecycle componentDidMount) components (for
Methods cannot be used in example,
functional components. componentDidMount).
Constructors are not Constructor is used as it
Constructor used. needs to store state.
State Uses this.state and
Uses hooks like useState
Manageme this.setState for state
for managing state.
nt management.
20. Explain one way data binding in React?
ReactJS uses one-way data binding which can be Component to
View or View to Component. It is also known as one-way data
flow, which means the data has one, and only one way to be
transferred to other parts of the application. In essence, this
means child components are not able to update the data that is
coming from the parent component. It is easy to debug and less
prone to errors.
21. What is Context API in React?
The Context API is a way to share data (such as theme, language
preference, etc.) across components without having to pass
props down manually at every level. It provides a Provider
component to set the value and a Consumer component or
useContext() hook to access it.
22. What is the role of shouldComponentUpdate() in
React?
shouldComponentUpdate() is a lifecycle method that allows you
to control whether a component should re-render when it
receives new props or state. If it returns false, React will skip the
re-render process for that component.
23. What is the use of dangerouslySetInnerHTML in
React?
dangerouslySetInnerHTML is an attribute used to set raw HTML
inside a component. It is generally discouraged because it can
expose the application to XSS (cross-site scripting) attacks, but it
is sometimes used for rendering third-party HTML content.
24. What are Pure Components in React?
A Pure Component is a type of React component that only re-
renders if the props or state it receives change. React provides
React.PureComponent, which is a base class that automatically
performs a shallow comparison of props and state to determine if
a re-render is necessary.
25. What is the significance of setState() in React?
setState() is a method used to update the state of a component.
When the state is updated, React re-renders the component and
its child components to reflect the changes.
React Intermediate Interview Questions
Here, we cover all intermediate level react interview questions
with answers, that recommeded for freshers as well as for
experienced professionals having 1 – 2 years of experience.
26. What is conditional rendering in React?
Conditional rendering in React involves selectively rendering
components based on specified conditions. By evaluating these
conditions, developers can control which components are
displayed, allowing for dynamic and responsive user interfaces in
React applications.
Let us look at this sample code to understand conditional
rendering.
{isLoggedIn == false ? <DisplayLoggedOut /> :
<DisplayLoggedIn />}
Here if the boolean isLoggedIn is false then the
DisplayLoggedOut component will be rendered otherwise
DisplayLoggedIn component will be rendered.
27. What is react router?
React Router is a standard library for routing in React. It enables
the navigation among views of various components in a React
Application, allows changing the browser URL, and keeps the UI
in sync with the URL.
To install react router type the following command.
npm i react-router-dom
28. Explain the components of a react-router.
The main components of a react-router are:
1. Router(usually imported as BrowserRouter): It is
the parent component that is used to store all of the
other components. Everything within this will be part of
the routing functionality
2. Switch: The switch component is used to render only the
first route that matches the location rather than
rendering all matching routes.
3. Route: This component checks the current URL and
displays the component associated with that exact path.
All routes are placed within the switch components.
4. Link: The Link component is used to create links to
different routes.
29. Explain the lifecycle methods of components
A React Component can go through four stages of its life as
follows.
Initialization: This is the stage where the component is
constructed with the given Props and default state. This
is done in the constructor of a Component Class.
Mounting: Mounting is the stage of rendering the JSX
returned by the render method itself.
Updating: Updating is the stage when the state of a
component is updated and the application is repainted.
Unmounting: As the name suggests Unmounting is the
final step of the component lifecycle where the
component is removed from the page.
30. Explain the methods used in mounting phase of
components
Mounting is the phase of the component lifecycle when the
initialization of the component is completed and the component
is mounted on the DOM and rendered for the first time on the
webpage. he mounting phase consists of two such predefined
functions as described below
componentWillMount() Function: This function is invoked
right before the component is mounted on the DOM.
componentDidMount() Function: This function is invoked
right after the component is mounted on the DOM.
31. What is this.setState function in React?
We use the setState() method to change the state object. It
ensures that the component has been updated and calls for re-
rendering of the component. The state object of a component
may contain multiple attributes and React allows using setState()
function to update only a subset of those attributes as well as
using multiple setState() methods to update each attribute value
independently.
32. What is the use of ref in React?
Refs are a function provided by React to access the DOM
element and the React element that you might have created on
your own. They are used in cases where we want to change the
value of a child component, without making use of props and all.
They have wide functionality as we can use callbacks with them.
The syntax to use ref is :
const node = this.myCallRef.current;
33. What are hooks in React?
Hooks are a new addition in React 16.8. They let developers use
state and other React features without writing a class. Hooks
doesn’t violate any existing React concepts. Instead, Hooks
provide a direct API to react concepts such as props, state,
context, refs and life-cycle
34. Explain the useState hook in React?
The most used hook in React is the useState() hook. Using this
hook we can declare a state variable inside a function but only
one state variable can be declared using a single useState()
hook. Whenever the useState() hook is used, the value of the
state variable is changed and the new variable is stored in a new
cell in the stack.
Syntax:
const [state, setState] = useState(initialState);
state: The current state value.
setState: A function used to update the state value.
initialState: The initial value of the state.
35. Explain the useEffect hook in React?
The useEffect hook in React eliminates the side effect of using
class based components. It is used as an alternative to
componentDidUpdate() method. The useEffect hook accepts two
arguments where second argument is optional.
useEffect(function, dependency)
The dependency decides when the component will be updated
again after rendering.
36. What is React Fragments?
when we are trying to render more than one root element we
have to put the entire content inside the ‘div’ tag which is not
loved by many developers. So since React 16.2
version, Fragments were introduced, and we use them instead of
the extraneous ‘div’ tag. The following syntax is used to create
fragment in react.
<React.Fragment>
<h2>Child-1</h2>
<p> Child-2</p>
</React.Fragment>
37. What is a react developer tool?
React Developer Tools is a Chrome DevTools extension for the
React JavaScript library. A very useful tool, if you are working on
React applications. This extension adds React debugging tools to
the Chrome Developer Tools. It helps you to inspect and edit the
React component tree that builds the page, and for each
component, one can check the props, the state, hooks, etc.
38. How to use styles in ReactJS?
CSS modules are a way to locally scope the content of your CSS
file. We can create a CSS module file by naming our CSS file as
App.modules.css and then it can be imported inside App.js file
using the special syntax mentioned below.
Syntax:
import styles from './App.module.css';
39. Explain styled components in React?
Styled-component Module allows us to write CSS within
JavaScript in a very modular and reusable way in React. Instead
of having one global CSS file for a React project, we can use
styled-component for enhancing the developer experience. It
also removes the mapping between components and styles –
using components as a low-level styling construct
The command to install styled components is
npm i styled-components
Using the below code we can custom style a button in React
import styled from 'styled-components'
const Button = styled.div`
width : 100px ;
cursor: pointer ;
text-decoration : none;
`
export default Button;
40. What is prop drilling and its disadvantages?
Prop drilling is basically a situation when the same data is being
sent at almost every level due to requirements in the final level.
The problem with Prop Drilling is that whenever data from the
Parent component will be needed, it would have to come from
each level, Regardless of the fact that it is not needed there and
simply needed in last.
41. What is conditional rendering in React?
Conditional rendering in React is used when you want to render
different UI elements based on certain conditions. For example,
rendering a login button if a user is not logged in or rendering a
logout button when the user is logged in.
const isLoggedIn = true;
return (
<div>
{isLoggedIn ?<button>Logout</button> : <button>Login</button>}
</div>
);
42. What are controlled components in React?
Controlled components are React components where the form
data is handled by the state within the component. The form
element’s value is controlled via the React state, making the
form elements responsive to changes.
For further reading, check out our dedicated article
on Intermediate ReactJS Intermediate Interview
Questions. Inside, you’ll discover over 20 questions with
detailed answers.
React Interview Questions for Experienced
Here, we cover advanced react interview questions with
answers for experienced professionals, who have over 5+ years
of experience.
43. What is custom hooks in React?
Custom hooks are normal JavaScript functions whose names
start with “use” and they may call other hooks. We use custom
hooks to maintain the DRY concept that is Don’t Repeat Yourself.
It helps us to write a logic once and use it anywhere in the code.
44. How to optimize a React code?
We can improve our react code by following these practices:
Using binding functions in constructors
Eliminating the use of inline attributes as they slow the
process of loading
Avoiding extra tags by using React fragments
Lazy loading
45. What is the difference between useref and
createRef in React ?
Here is the difference table of useref and createRef in React
Features useRef createRef
Type It is a hook. It is a function.
It uses the same ref It creates a new ref
Reference throughout the every time component
Lifecycle component’s lifecycle. re-renders.
Persistence It saves its value
It creates a new ref for
Across between re-renders in a
every re-render.
Renders functional component.
It returns a mutable ref It returns a read-only ref
Return Value object (i.e., can be object (cannot be
changed). modified directly).
Used for accessing DOM
Used for class
elements, persisting
components, especially
Use Case values, or managing
when referencing DOM
timers in functional
elements.
components.
const myRef =
Example const myRef = useRef();
React.createRef();
46. What is react-redux?
React-redux is a state management tool which makes it easier
to pass these states from one component to another irrespective
of their position in the component tree and hence prevents the
complexity of the application. As the number of components in
our application increases it becomes difficult to pass state as
props to multiple components. To overcome this situation we use
react-redux
47. What are benefits of using react-redux?
They are several benfits of using react-redux such as:
It provides centralized state management i.e. a single
store for whole application
It optimizes performance as it prevents re-rendering of
component
Makes the process of debugging easier
Since it offers persistent state management therefore
storing data for long times become easier
48. Explain the core components of react-redux?
There are four fundamental concepts of redux in react which
decide how the data will flow through components
Redux Store: It is an object that holds the application
state
Action Creators: These are functions that return actions
(objects).
Actions: Actions are simple objects which conventionally
have two properties- type and payload
Reducers: Reducers are pure functions that update the
state of the application in response to actions
49. How can we combine multiple reducers in
React?
When working with Redux we sometimes require multiple
reducers. In many cases, multiple actions are needed, resulting
in the requirement of multiple reducers. However, this can
become problematic when creating the Redux store. To manage
the multiple reducers we have function called combineReducers
in the redux. This basically helps to combine multiple reducers
into a single unit and use them.
Syntax
import { combineReducers } from "redux";
const rootReducer = combineReducers({
books: BooksReducer,
activeBook: ActiveBook
});
50. Explain CORS in React?
In ReactJS, Cross-Origin Resource Sharing (CORS) refers to the
method that allows you to make requests to the server deployed
at a different domain. As a reference, if the frontend and
backend are at two different domains, we need CORS there.
We can setup CORS evironment in frontend using two methods:
axios
fetch
51. What is axios and how to use it in React?
Axios, which is a popular library is mainly used to send
asynchronous HTTP requests to REST endpoints. This library is
very useful to perform CRUD operations.
This popular library is used to communicate with the
backend. Axios supports the Promise API, native to JS
ES6.
Using Axios we make API requests in our application.
Once the request is made we get the data in Return, and
then we use this data in our project.
To install axios package in react use the following command.
npm i axios
52. Write a program to create a counter with
increment and decrement?
We can create the counter app with increment and decrement by
writing the below code in the terminal:
import React, { useState } from "react";
const App = () => {
const [counter, setCounter] = useState(0)
const handleClick1 = () => {
setCounter(counter + 1)
}
const handleClick2 = () => {
setCounter(counter - 1)
}
return (
<div>
<div>
{counter}
</div>
<div className="buttons">
<button onClick={handleClick1}>
Increment
</button>
<button onClick={handleClick2}>
Decrement
</button>
</div>
</div>
)
}
export default App
Output:
Counter App using React
53. Explain why and how to update state of
components using callback?
It is advised to use a callback-based approach to update the
state using setState because it solves lots of bugs upfront that
may occur in the future.We can use the following syntax to
update state using callback
this.setState(st => {
return(
st.stateName1 = state1UpdatedValue,
st.stateName2 = state2UpdatedValue
)
})
54. What is React-Material UI?
React Material UI is an open-source React component library,
offering prebuilt components for creating React applications.
Developed by Google in 2014, it’s compatible with JavaScript
frameworks like Angular.js and Vue.js. Renowned for its quality
designs and easy customization, it’s favored by developers for
rapid development.
55. What is flux architecture in redux?
Flux architecture in Redux is a design pattern used for managing
application state in a unidirectional data flow. In this
architecture, actions are dispatched to modify the store, which
holds the entire application state. The store sends the updated
state to the view (UI), and the cycle repeats when new actions
are triggered. Redux follows this structure to ensure a
predictable and maintainable state management system for
large applications.
56. What are custom hooks in React?
Custom hooks are user-defined functions that use built-in hooks
like useState, useEffect, etc., to reuse stateful logic across
components. They allow you to extract and share common logic.
57. How can you optimize React performance?
Optimizing React performance can be achieved using:
React.memo() for preventing unnecessary re-renders.
Lazy loading components with React.lazy() and
Suspense.
Using useMemo() and useCallback() hooks to memoize
values and functions.
Avoiding unnecessary state updates.
58. What is the Strict Mode in React?
Strict Mode in React is a tool that helps developers find and fix
problems in their app while developing. It only works in
development and doesn’t affect the app when it’s running in
production. When enabled, it checks for potential issues, such as
old features that should no longer be used, and gives warnings
to help avoid bugs.
We can enable the strict mode by by wrapping your application
or specific components inside the <React.StrictMode>.
import React from "react";
import ReactDOM from "react-dom";
const App = () => {
return (
<div>
<h1>Hello, World!</h1>
</div>
);
};
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
59. What is Redux and how does it work with React?
Redux is a state management library that helps manage the
application state globally. It uses actions, reducers, and a central
store to control state. React-Redux is used to connect Redux
state to React components.
60. How does React handle concurrency?
React’s Concurrent Mode is a set of features that help React
apps stay responsive and gracefully adjust to the user’s device
capabilities and network speed. It allows React to interrupt
rendering and prioritize high-priority tasks.
61. How does React handle server-side rendering
(SSR)?
Server-side rendering (SSR) is the process of rendering a React
application on the server and sending the fully rendered HTML to
the client. This improves the initial page load performance and
SEO.
62. How to create forms in React?
Creating forms in React involves handling user input and
managing the form’s state. In React, form elements like
<input>, <textarea>, and <select> are controlled components,
meaning their values are controlled by the React state.
Create the State for the Form: Use the useState hook
to manage form input values.
Set the Value of Form Elements: Bind the form
elements’ value attribute to the corresponding state
variable to make the inputs controlled.
Handle User Input: Use an onChange event handler to
update the state whenever the user types in the form
fields.
Submit the Form: Handle the form submission with an
onSubmit event, and prevent the default behavior to stop
the page from refreshing.
import React, { useState } from 'react';
function MyForm() {
// State to store input values
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
// Handle input change for each field
const handleNameChange = (e) => setName(e.target.value);
const handleEmailChange = (e) => setEmail(e.target.value);
const handleMessageChange = (e) => setMessage(e.target.value);
// Handle form submission
const handleSubmit = (e) => {
e.preventDefault(); // Prevent default form submission
behavior
console.log('Form submitted:', { name, email, message });
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Name:</label>
<input type="text" value={name}
onChange={handleNameChange} />
</div>
<div>
<label>Email:</label>
<input type="email" value={email}
onChange={handleEmailChange} />
</div>
<div>
<label>Message:</label>
<textarea value={message}
onChange={handleMessageChange} />
</div>
<button type="submit">Submit</button>
</form>
);
}
export default MyForm;
Output:
React Form
63. What is Lazy Loading in React?
Lazy Loading in React is a technique used to load components
only when they are needed, instead of loading everything at
once when the app starts. This helps improve the performance of
the app by reducing the initial loading time.
In React, React.lazy() is used to implement lazy loading for
components, which allows you to split your code into smaller
bundles and load them only when required.