Skip to main content
InterviewHubPRO
HomeTracksSection 3: React Core & Hooks (407 Qs)
Section 3 of 64407 Questions (1 Per Page)

React Core Architecture, Hooks & Systems Performance Master Interview Bank

Virtual DOM, Fiber reconciliation architecture, Concurrent Mode, React Server Components (RSC), Suspense, Server Actions, Hooks, and state management.

Curriculum Roadmap & Learning Path

8 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.8 Connected Milestones
407 of 407 Qs

General

77 Questions
1
Most AskedJuniorCode#react#General

What is React?

React (aka React.js or ReactJS) is an open-source front-end JavaScript library for building user interfaces based on components. It's used for handling the view layer in web and mobile applications, and allows developers to create reusable UI components and manage the state of those components efficiently.

2
Junior#react#General

What is the history behind React evolution?

The history of ReactJS started in 2010 with the creation of XHP. XHP is a PHP extension which improved the syntax of the language such that XML document fragments become valid PHP expressions and the primary purpose was used to create custom and reusable HTML elements.

3
Junior#react#General

What are the major features of React?

React offers a powerful set of features that have made it one of the most popular JavaScript libraries for building user interfaces.

4
JuniorCode#react#General

What is JSX?

JSX stands for JavaScript XML and it is an XML-like syntax extension to ECMAScript. Basically it just provides the syntactic sugar for the React.createElement(type, props...children) function, giving us expressiveness of JavaScript along with HTML like template syntax.

5
JuniorCode#Components

What is the difference between an Element and a Component?

Think of elements as the instructions for creating UI, and components as reusable blueprints that combine logic and structure to generate those instructions.

6
MidCode#Components

How to create components in React?

Components are the building blocks of creating User Interfaces(UI) in React. There are two possible ways to create a component.

7
Mid#Components

When to use a Class Component over a Function Component?

Note when using react-error-boundary: ErrorBoundary is a client component. You can only pass props to it that are seriali.

8
Junior#Components

What are Pure Components?

Pure components are the components which render the same output for the same state and props. In function components, you can achieve these pure components through memoization using React.memo().

9
Junior#react#General

What is state in React?

State of a component is an object that holds some information that may change over the lifetime of the component. The important point is whenever the state object changes, the component re-renders. It is always recommended to make our state as simple as possible and minimi.

10
JuniorCode#Components

What are props in React?

Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation similar to HTML-tag attributes. Here, the data is passed down from a parent component to a child component.

11
Junior#Components

What is the difference between state and props?

In React, both state and props are plain JavaScript objects, but they serve different purposes and have distinct behaviors.

12
JuniorCode#react#General

What is the difference between HTML and React event handling?

In HTML, the event name usually represents in lowercase as a convention.

13
JuniorCode#react#General

What are synthetic events in React?

SyntheticEvent is a cross-browser wrapper around the browser's native event. Its API is same as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers. The native events can be accessed directly from synthetic events using nativeEvent attribute.

14
JuniorCode#react#General

What are inline conditional expressions?

You can use either if statements or ternary expressions which are available in JS(and JSX in React) to conditionally execute or render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator &&.

15
JuniorCode#Data Structures

What is "key" prop and what is the benefit of using it in arrays of elements?

A key is a special attribute you should include when mapping over arrays to render data. Key prop helps React identify which items have changed, are added, or are removed.

16
Most AskedJunior#react#General

What is Virtual DOM?

The Virtual DOM (VDOM) is a lightweight, in-memory representation of Real DOM used by libraries like React to optimize rendering performance.

17
Most AskedMidCode#react#General

How Virtual DOM works?

The Virtual DOM works in five simple steps.

18
Most AskedJuniorCode#react#General

What is the difference between Shadow DOM and Virtual DOM?

The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.

19
Most AskedSenior#react#General

What is React Fiber?

React Fiber is the new reconciliation engine in React, introduced in React 16. It’s a complete rewrite of React’s core algorithm(old stack-based algorithm) for rendering and updating the UI. Fiber enhances React's ability to handle asynchronous rendering, prioritization of updates, and concurrency.

20
Most AskedSenior#react#General

What is the main goal of React Fiber?

The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

21
Junior#Components

What are controlled components?

A controlled component is a React component that fully manages the form element's state(e.g, elements like , , or )) using React's internal state mechanism. i.e, The component does not manage its own internal state — instead, React acts as the single source of truth for form data.

22
JuniorCode#Components

What are uncontrolled components?

The Uncontrolled components are form elements (like , , or ) that manage their own state internally via the DOM, rather than through React state. You can query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

23
JuniorCode#react#General

What is the difference between createElement and cloneElement?

Both React.createElement and React.cloneElement are used to work with React elements, but they serve different purposes.

24
JuniorCode#react#General

What is Lifting State Up in React?

When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor. That means if two child components share the same data from its parent, then move the state to parent instead of maintaining local state in both of the child components.

25
JuniorCode#Components

What are Higher-Order Components?

A higher-order component (HOC) is a function that takes a component and returns a new enhanced component with additional props, behavior, or data. It’s a design pattern based on React’s compositional nature, allowing you to reuse logic across multiple components without modifying their internals.

26
JuniorCode#react#General

What is children prop?

The children prop is a special prop in React used to pass elements between the opening and closing tags of a component. It is commonly used in layout and wrapper componnents.

27
MidCode#react#General

How to write comments in React?

The comments in React/JSX are similar to JavaScript Multiline comments but are wrapped in curly braces.

28
Most AskedSeniorCode#react#General

What is reconciliation?

Reconciliation is the process through which React updates the Browser DOM and makes React work faster. React use a diffing algorithm so that component updates are predictable and faster. React would first calculate the difference between the real DOM and the copy of DOM (Virtual DOM) when there's an update of components.

29
MidCode#react#General

Does the lazy function support named exports?

No, React.lazy currently supports default exports only. If the component you want to import is exported using named exports, you can create an intermediate module that re-exports it as the default, or resolve it using .then() on the dynamic import promise.

30
MidCode#react#General

Why React uses className over class attribute?

React uses className instead of class because of a JavaScript naming conflict with the class keyword.

31
Most AskedJuniorCode#react#General

What are fragments?

It's a common pattern or practice in React for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM. You need to use either Fragment or a shorter syntax having empty tag (<>).

32
Most AskedMidCode#Docker & Containers

Why fragments are better than container divs?

Fragments are a bit faster and use less memory by not creating an extra DOM node • Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationships, and adding divs in the middle makes it hard to keep the • The DOM Inspector is less cluttered.

33
JuniorCode#react#General

What are portals in React?

A Portal is a React feature that enables rendering children into a DOM node that exists outside the parent component's DOM hierarchy, while still preserving the React component hierarchy. Portals help avoid CSS stacking issues—for example, elements with position: fixed may not behave as expected inside a parent with transform.

34
JuniorCode#Components

What are stateless components?

If the behaviour of a component is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components.

35
JuniorCode#Components

What are stateful components?

If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These stateful components are either function components with hooks or class components.

36
MidCode#Components#Forms

How to apply validation on props in React?

When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type. If the type is incorrect, React will generate warning messages in the console. It's disabled in production mode due to performance impact.

37
JuniorCode#react#General

What are the advantages of React?

Increases the application's performance with Virtual DOM • JSX makes code easy to read and write • It renders both on client and server side (SSR) • Easy to integrate with frameworks (Angular, Backbone) since it is only a view library.

38
JuniorCode#react#General

What are the limitations of React?

React is just a view library, not a full framework • There is a learning curve for beginners who are new to web development • Integrating React into a traditional MVC framework requires some additional configuration • The code complexity increases with inline templating and JSX.

39
JuniorCode#react#General

What are the recommended ways for static type checking?

Modern Recommendation (2026): TypeScript is the industry standard for type checking in React applications.

40
JuniorCode#react#General

What is the use of react-dom package?

The react-dom package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are: render() • hydrate() • unmountComponentAtNode() • findDOMNode().

41
JuniorCode#react#General

What is ReactDOMServer?

The ReactDOMServer object enables you to render components to static markup (typically used on node server). This object is mainly used for server-side rendering (SSR). The following methods can be used in both the server and browser environments: renderToString() • renderToStaticMarkup().

42
MidCode#react#General

How to use innerHTML in React?

The dangerouslySetInnerHTML attribute is React's replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.

43
MidCode#react#General

How to use styles in React?

The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.

44
MidCode#react#General

How events are different in React?

Handling events in React elements has some syntactic differences: React event handlers are named using camelCase, rather than lowercase • With JSX you pass a function as the event handler, rather than a string.

45
Most AskedJunior#react#General

What is the impact of indexes as keys?

Keys should be stable, predictable, and unique so that React can keep track of elements.

46
MidCode#Components

How do you conditionally render components?

In some cases you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.

47
MidCode#Components

Why we need to be careful when spreading props on DOM elements?

When we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice. Instead we can use prop destructuring with ...rest operator, so it will add only required props.

48
MidCode#Components

How do you memoize a component?

In React, you can memoize a functional component using React.memo(). It wraps your component to prevent unnecessary re-renders if its props have not changed (via shallow comparison).

49
MidCode#SSR & Hydration

How you implement Server Side Rendering or SSR?

React is already equipped to handle rendering on Node servers. A special version of the DOM renderer is available, which follows the same pattern as on the client side.

50
Mid#react#General

How to enable production mode in React?

You should use Webpack's DefinePlugin method to set NODE_ENV to production, by which it strip out things like propType validation and extra warnings. Apart from this, if you minify the code, for example, Uglify's dead-code elimination to strip out development only code and comments, it will drastically reduce the si.

51
MidCode#Components#Hooks

Do Hooks replace render props and higher order components?

Both render props and higher-order components render only a single child but in most of the cases Hooks are a simpler way to serve this by reducing nesting in your tree.

52
JuniorCode#Components

What is a switching component?

A switching component is a component that renders one of many components. We need to use object to map prop values to components.

53
JuniorCode#react#General

What are the Pointer Events supported in React?

Pointer Events provide a unified way of handling all input events. In the old days we had a mouse and respective event listeners to handle them but nowadays we have many devices which don't correlate to having a mouse, like phones with touch surface or pens.

54
Mid#Components#HTTP & REST APIs

Why should component names start with capital letter?

If you are rendering your component using JSX, the name of that component has to begin with a capital letter otherwise React will throw an error as an unrecogni.

55
Mid#react#General

Are custom DOM attributes supported in React v16?

Note: This question references React v16, which is outdated. The information below applies to React 16+, including current versions (React 18/19).

56
MidCode#react#General

How to loop inside JSX?

You can simply use Array.prototype.map with ES6 arrow function syntax.

57
MidCode#Components

How do you access props in attribute quotes?

React (or JSX) doesn't support variable interpolation inside an attribute value. The below representation won't work.

58
JuniorCode#Data Structures

What is React proptype array with shape?

If you want to pass an array of objects to a component with a particular shape then use React.PropTypes.shape() as an argument to React.PropTypes.arrayOf().

59
MidCode#react#General

How to conditionally apply class attributes?

You shouldn't use curly braces inside quotes because it is going to be evaluated as a string.

60
JuniorCode#react#General

What is the difference between React and ReactDOM?

The react package contains React.createElement(), React.Component, React.Children, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components.

61
MidCode#react#General

Why ReactDOM is separated from React?

The React team worked on extracting all DOM-related features into a separate library called ReactDOM. React v0.14 is the first release in which the libraries are split.

62
MidCode#react#General

How to use React label element?

If you try to render a element bound to a text input using the standard for attribute, then it produces HTML missing that attribute and prints a warning to the console.

63
MidCode#react#General

How to combine multiple inline style objects?

You can use spread operator in regular React.

64
Mid#react#General

How to re-render the view when the browser is resized?

You can use the useState hook to manage the width and height state variables, and the useEffect hook to add and remove the `resi.

65
MidCode#react#General

How to pretty print JSON with React?

We can use tag so that the formatting of the JSON.stringify() is retained.

66
MidCode#Components

Why can't you update props in React?

The React philosophy is that props should be immutable(read only) and top-down. This means that a parent can send any prop values to a child, but the child can't modify received props.

67
MidCode#react#General

How to focus an input element on page load?

You need to use useEffect hook to set focus on input field during page load time for functional component.

68
MidCode#react#General

How can we find the version of React at runtime in the browser?

You can use React.version to get the version.

69
MidCode#Routing

How to add Google Analytics for React Router?

Add a listener on the history object to record each page view.

70
MidCode#react#General

How do you apply vendor prefixes to inline styles in React?

React does not apply vendor prefixes automatically. You need to add vendor prefixes manually.

71
MidCode#Components

How to import and export components using React and ES6?

You should use default for exporting the components.

72
JuniorCode#Components

What are the exceptions on React component naming?

The component names should start with an uppercase letter but there are few exceptions to this convention. The lowercase tag names with a dot (property accessors) are still considered as valid component names. For example, the below tag can be compiled to a valid component.

73
Most AskedMidCode#Async & Promises

Is it possible to use async/await in plain React?

Yes, you can use async/await in plain React, as long as your JavaScript environment supports ES2017+. Nowadays most modern browsers and build tools support ES2017+ version. If you're using Create React App, Next.js, Remix, or any modern React setup, async/await is supported out of the box through Babel.

74
JuniorCode#react#General

What are the common folder structures for React?

There are two common practices for React project file structure.

75
JuniorCode#react#General

What are the popular packages for animation?

React Transition Group and React Motion are popular animation packages in React ecosystem.

76
JuniorCode#react#General

What is the benefit of styles modules?

It is recommended to avoid hard coding style values in components. Any values that are likely to be used across different UI components should be extracted into their own modules.

77
JuniorCode#react#General

What are the popular React-specific linters?

ESLint is a popular JavaScript linter. There are plugins available that analyse specific code styles. One of the most common for React is an npm package called eslint-plugin-react. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types.

Part 2: React Router & Navigation (78 - 88)

17 Questions
78
JuniorCode#Routing

What is React Router?

React Router is a powerful routing library built on top of React that helps you add new screens and flows to your application incredibly quickly, all while keeping the URL in sync with what's being displayed on the page.

79
MidCode#Routing

How React Router is different from history library?

React Router is a wrapper around the history library which handles interaction with the browser's window.history with its browser and hash histories. It also provides memory history which is useful for environments that don't have global history, such as mobile app development (React Native) and unit testing with Node.

80
JuniorCode#Components#Routing

What are the <Router> components of React Router v6?

React Router v6 provides below 4 Router components: BrowserRouter:Uses the HTML5 history API for standard web apps • HashRouter:Uses hash-based routing for static servers • MemoryRouter:Uses in-memory routing for testing and non-browser environments • StaticRouter:Provides static routing for server-side rendering (SSR).

81
JuniorCode#Routing

What is the purpose of push() and replace() methods of history?

A history instance has two methods for navigation purpose.: push() • replace().

82
MidCode#Routing

How do you programmatically navigate using React Router v4?

There are three different ways to achieve programmatic routing/navigation within components.

83
MidCode#Routing

How to get query parameters in React Router v4?

The ability to parse query strings was taken out of React Router v4 because there have been user requests over the years to support different implementation. So the decision has been given to users to choose the implementation they like. The recommended approach is to use query strings library.

84
MidCode#Routing

Why you get "Router may have only one child element" warning?

You have to wrap your Route's in a Switch block because Switch is unique in that it renders a route exclusively.

85
MidCode#Routing

How to pass params to history.push method in React Router v4?

While navigating you can pass props to the history object.

86
MidCode#Routing

How to implement _default_ or _NotFound_ page?

A Switch renders the first child Route that matches. A Route with no path always matches. So you just need to simply drop path attribute as below.

87
MidCode#Routing

How to get history on React Router v4?

Create a module that exports a history object and import this module across the project.

88
MidCode#Routing#Forms

How to perform automatic redirect after login?

The react-router package provides Redirect component in React Router. Rendering a Redirect will navigate to a new location. Like server-side redirects, the new location will override the current location in the history stack.

89
JuniorCode#Routing

What is React Intl?

React Intl is an open-source internationalization (i18n) library created by FormatJS for React applications. It provides React components and an API to format dates, numbers, strings, and handle pluralization across different languages and locales.

90
Junior#Routing

What are the main features of React Intl?

Display numbers with separators • Display dates and times correctly • Display dates relative to "now" • Plurali.

91
JuniorCode#Routing#Forms

What are the two ways of formatting in React Intl?

The library provides two ways to format strings, numbers, and dates: Using react components.

92
MidCode#Routing#Forms

How to use <FormattedMessage> as placeholder using React Intl?

The components from react-intl return elements, not plain text, so they can't be used for placeholders, alt text, etc. In that case, you should use lower level API formatMessage().

93
MidCode#Routing

How to access current locale with React Intl?

You can get the current locale in any component of your application using injectIntl().

94
MidCode#Routing#Forms

How to format date using React Intl?

The injectIntl() higher-order component will give you access to the formatDate() method via the props in your component. The method is used internally by instances of FormattedDate and it returns the string representation of the formatted date.

Part 4: React Testing & Jest (95 - 100)

6 Questions
95
JuniorCode#Testing

What is Shallow Renderer in React testing?

Shallow rendering is useful for writing unit test cases in React. It lets you render a component one level deep and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered.

96
JuniorCode#Testing

What is TestRenderer package in React?

This package provides a renderer that can be used to render components to pure JavaScript objects, without depending on the DOM or a native mobile environment. This package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a ReactDOM or React Native without using a browser or jsdom.

97
JuniorCode#Testing

What is the purpose of ReactTestUtils package?

ReactTestUtils are provided in the with-addons package and allow you to perform actions against a simulated DOM for the purpose of unit testing.

98
JuniorCode#Testing

What is Jest?

Jest is a JavaScript unit testing framework created by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It's often used for testing components.

99
JuniorCode#Testing

What are the advantages of Jest over Jasmine?

Automatically finds tests to execute in your source code • Automatically mocks dependencies when running your tests • Allows you to test asynchronous code synchronously • Runs your tests with a fake DOM implementation (via jsdom) so that your tests can be run on the command line.

100
MidCode#Testing

Give a simple example of Jest test case

Let's write a test for a function that adds two numbers in sum.js file.

Part 5: React Redux State Management (101 - 134)

34 Questions
101
Most AskedJunior#State Management

What is flux?

Flux is an application architecture (not a framework or library) designed by Facebook to manage data flow in React applications. It was created as an alternative to the traditional MVC (Model-View-Controller) pattern, and it emphasi.

102
Most AskedJunior#State Management

What is Redux?

Redux is a predictable state container for JavaScript applications, most commonly used with React. It helps you manage and centrali.

103
Most AskedJuniorCode#State Management

What are the core principles of Redux?

Redux follows three fundamental principles: Single source of truth: The state of your whole application is stored in an object tree within a single store.

104
Most AskedJuniorCode#State Management

What are the downsides of Redux compared to Flux?

Immutability is essential.

105
Most AskedJuniorCode#Components#State Management

What is the difference between mapStateToProps() and mapDispatchToProps()?

mapStateToProps() is a utility which helps your component get updated state (which is updated by some other components).

106
Most AskedMidCode#State Management

Can I dispatch an action in reducer?

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

107
Most AskedMidCode#Components#State Management

How to access Redux store outside a component?

You just need to export the store from the module where it created with createStore(). Also, it shouldn't pollute the global window object.

108
Most AskedJuniorCode#State Management

What are the drawbacks of MVW pattern?

DOM manipulation is very expensive which causes applications to behave slow and inefficient • Due to circular dependencies, a complicated model was created around models and views • Lot of data changes happens for collaborative applications(like Google Docs).

109
Most AskedMidCode#RxJS#State Management

Are there any similarities between Redux and RxJS?

These libraries are very different for very different purposes, but there are some vague similarities.

110
Most AskedMidCode#State Management

How to reset state in Redux?

You need to write a root reducer in your application which delegate handling the action to the reducer generated by combineReducers().

111
Most AskedJunior#State Management

What is the difference between React context and React Redux?

You can use Context in your application directly and is going to be great for passing down data to deeply nested components which what it was designed for.

112
Most AskedMidCode#State Management

Why are Redux state functions called reducers?

Reducers always return the accumulation of the state (based on all previous and current actions). Therefore, they act as a reducer of state. Each time a Redux reducer is called, the state and action are passed as parameters. This state is then reduced (or accumulated) based on the action, and then the next state is returned.

113
Most AskedMidCode#State Management

How to make AJAX request in Redux?

You can use redux-thunk middleware which allows you to define async actions.

114
Most AskedMidCode#Components#State Management

Should I keep all component's state in Redux store?

Keep your data in the Redux store, and the UI related state internally in the component.

115
Most AskedJuniorCode#State Management

What is the proper way to access Redux store?

The best way to access your store in a component is to use the connect() function, that creates a new component that wraps around your existing one. This pattern is called Higher-Order Components, and is generally the preferred way of extending a component's functionality in React.

116
Most AskedJuniorCode#Components#State Management

What is the difference between component and container in React Redux?

Component is a class or function component that describes the presentational part of your application.

117
Most AskedJuniorCode#State Management

What is the purpose of the constants in Redux?

Constants allows you to easily find all usages of that specific functionality across the project when you use an IDE. It also prevents you from introducing silly bugs caused by typos – in which case, you will get a ReferenceError immediately.

118
Most AskedJuniorCode#Components#State Management

What are the different ways to write mapDispatchToProps()?

There are a few ways of binding action creators to dispatch() in mapDispatchToProps().

119
Most AskedJuniorCode#Components#State Management

What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()?

If the ownProps parameter is specified, React Redux will pass the props that were passed to the component into your connect functions. So, if you use a connected component.

120
Most AskedMid#State Management

How to structure Redux top level directories?

Most of the applications has several top-level directories as below: Components: Used for dumb components unaware of Redux • Containers: Used for smart components connected to Redux • Actions: Used for all action creators, where file names correspond to part of the app.

121
Most AskedJuniorCode#State Management

What is redux-saga?

redux-saga is a library that aims to make side effects (asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better.

122
Most AskedJuniorCode#State Management

What is the mental model of redux-saga?

Saga is like a separate thread in your application, that's solely responsible for side effects. redux-saga is a redux middleware, which means this thread can be started, paused and cancelled from the main application with normal Redux actions, it has access to the full Redux application state and it can dispatch Redux actions as well.

123
Most AskedJuniorCode#State Management

What are the differences between call() and put() in redux-saga?

Both call() and put() are effect creator functions. call() function is used to create effect description, which instructs middleware to call the promise. put() function creates an effect, which instructs middleware to dispatch an action to the store.

124
Most AskedJuniorCode#State Management

What is Redux Thunk?

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch() and getState() as parameters.

125
Most AskedJuniorCode#State Management

What are the differences between redux-saga and redux-thunk?

Both Redux Thunk and Redux Saga take care of dealing with side effects. In most of the scenarios, Thunk uses Promises to deal with them, whereas Saga uses Generators. Thunk is simple to use and Promises are familiar to many developers, Sagas/Generators are more powerful but you will need to learn them.

126
Most AskedJunior#State Management

What is Redux DevTools?

Redux DevTools is a live-editing time-travel debugging environment for Redux with hot reloading, action replay, state diff inspection, and custom action dispatching.

127
Most AskedJuniorCode#State Management

What are the features of Redux DevTools?

Some of the main features of Redux DevTools are below: Lets you inspect every state and action payload • Lets you go back in time by cancelling actions • If you change the reducer code, each staged action will be re-evaluated • If the reducers throw, you will see during which action this happened, and what the error was.

128
Most AskedJuniorCode#State Management

What are Redux selectors and why use them?

Selectors are functions that take Redux state as an argument and return some data to pass to the component.

129
Most AskedJuniorCode#State Management#Forms

What is Redux Form?

Redux Form works with React and Redux to enable a form in React to use Redux to store all of its state. Redux Form can be used with raw HTML5 inputs, but it also works very well with common UI frameworks like Material UI, React Widgets and React Bootstrap.

130
Most AskedJunior#State Management#Forms

What are the main features of Redux Form?

Some of the main features of Redux Form are: Field values persistence via Redux store • Validation (sync/async) and submission • Formatting, parsing and normali.

131
Most AskedMidCode#State Management

How to add multiple middlewares to Redux?

You can use applyMiddleware().

132
Most AskedMidCode#State Management

How to set initial state in Redux?

You need to pass initial state as second argument to createStore.

133
Most AskedMid#State Management

How Relay is different from Redux?

Relay is similar to Redux in that they both use a single store. The main difference is that relay only manages state originated from the server, and all access to the state is used via GraphQL queries (for reading data) and mutations (for changing data).

134
Most AskedJuniorCode#State Management

What is an action in Redux?

Actions are plain JavaScript objects or payloads of information that send data from your application to your store. They are the only source of information for the store. Actions must have a type property that indicates the type of action being performed.

Part 7: Supported Libraries, Styling & Integrations (139 - 151)

13 Questions
139
JuniorCode#react#Supported Libraries

What is reselect and how it works?

Reselect is a memoized selector library for Redux (built into Redux Toolkit) that prevents expensive recalculations and unnecessary component re-renders.

140
JuniorCode#react#Supported Libraries

What is Flow?

Flow is a static type checker designed to find type errors in JavaScript. Flow types can express much more fine-grained distinctions than traditional type systems. For example, Flow helps you catch errors involving null, unlike most type systems.

141
JuniorCode#react#Supported Libraries

What is the difference between Flow and PropTypes?

Flow is a static analysis tool (static checker) which uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time.

142
MidCode#react#Supported Libraries

How to use Font Awesome icons in React?

The below steps followed to include Font Awesome in React: Install font-awesome.

143
JuniorCode#react#Supported Libraries

What is React Dev Tools?

React Developer Tools let you inspect the component hierarchy, including component props and state. It exists both as a browser extension (for Chrome and Firefox), and as a standalone app (works with other environments including Safari, IE, and React Native).

144
MidCode#react#Supported Libraries

Why is DevTools not loading in Chrome for local files?

If you opened a local HTML file in your browser (file://...) then you must first open Chrome Extensions and check Allow access to file URLs.

145
MidCode#react#Supported Libraries

How to use Polymer in React?

You need to follow below steps to use Polymer in React: Create a Polymer element.

146
JuniorCode#Vue & Nuxt

What are the advantages of React over Vue.js?

Gives more flexibility in large apps developing • Easier to test • Suitable for mobile apps creating • More information and solutions available.

147
JuniorCode#react#Supported Libraries

What is the difference between React and Angular?

Let's see the difference between React and Angular in a table format.

148
Mid#react#Supported Libraries

Why React tab is not showing up in DevTools?

When the page loads, React DevTools sets a global named REACTDEVTOOLSGLOBALHOOK__, then React communicates with that hook during initialization.

149
JuniorCode#Components

What are Styled Components?

styled-components is a JavaScript library for styling React applications. It removes the mapping between styles and components, and lets you write actual CSS augmented with JavaScript.

150
MidCode#Components

Give an example of Styled Components?

Lets create Title and Wrapper components with specific styles for each.

151
JuniorCode#react#Supported Libraries

What is Relay?

Relay is a JavaScript framework for providing a data layer and client-server communication to web applications using the React view layer.

Part 8: Advanced React Patterns, Portals & Performance (152 - 261)

110 Questions
152
JuniorCode#Forms#Performance

What are the main features of Reselect library?

Let's see the main features of Reselect library: Selectors can compute derived data, allowing Redux to store the minimal possible state • Selectors are efficient • Selectors are composable.

153
Most AskedMidCode#State Management#Forms

Can Redux only be used with React?

Redux can be used as a data store for any UI layer. The most common usage is with React and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and more. Redux simply provides a subscription mechanism which can be used by any other code.

154
Most AskedMidCode#State Management#Forms

Do you need to have a particular build tool to use Redux?

Redux is originally written in ES6 and transpiled for production into ES5 with Webpack and Babel. You should be able to use it regardless of your JavaScript build process. Redux also offers a UMD build that can be used directly without any build process at all.

155
Most AskedMidCode#State Management#Forms

How Redux Form initialValues get updated from state?

In Redux Form, to re-initialize form fields when the Redux store state changes (for example, after fetching data asynchronously), you set the enableReinitialize: true configuration flag when wrapping your component with reduxForm().

156
MidCode#Forms#Performance

How React PropTypes allow different types for one prop?

You can use the oneOfType() method of PropTypes.

157
MidCode#Components#Forms

Can I import an SVG file as react component?

You can import SVG directly as component instead of loading it as a file. This feature is available with react-scripts@2.0.0 and higher.

158
JuniorCode#Forms#Performance

What is render hijacking in react?

The concept of render hijacking is the ability to control what a component will output from another component. It means that you decorate your component by wrapping it into a Higher-Order component. By wrapping, you can inject additional props or make other changes, which can cause changing logic of rendering.

159
MidCode#Components#Forms

How to pass numbers to React component?

We can pass numbers as props to React component using curly braces {} where as strings in double quotes "" or single quotes ''.

160
Most AskedSenior#State Management#Forms

Do I need to keep all my state into Redux? Should I ever use react internal state?

It is up to the developer's decision, i.e., it is developer's job to determine what kinds of state make up your application, and where each piece of state should live. Some users prefer to keep every single piece of data in Redux, to maintain a fully seriali.

161
JuniorCode#Forms#Performance

What is the purpose of registerServiceWorker in React?

React creates a service worker for you without any configuration by default. The service worker is a web API that helps you cache your assets and other files so that when the user is offline or on a slow network, he/she can still see results on the screen, as such, it helps you build a better user experience, that's what you should...

162
JuniorCode#Forms#Performance

What is React memo function?

Class components can be restricted from re-rendering when their input props are the same using PureComponent or shouldComponentUpdate. Now you can do the same with function components by wrapping them in React.memo.

163
JuniorCode#Forms#Performance

What is React lazy function?

The React.lazy() function lets you render a dynamic import as a regular component. This enables code-splitting by loading the bundle containing the component only when it is actually rendered on screen. It must be wrapped inside a React.Suspense boundary.

164
MidCode#Forms#Performance

How to prevent unnecessary updates using setState?

You can compare the current value of the state with an existing state value and decide whether to rerender the page or not. If the values are the same then you need to return null to stop re-rendering otherwise return the latest state value.

165
MidCode#Forms#Performance

How do you render Array, Strings and Numbers in React 16 Version?

Note: This question references React 16. These features remain valid in current React versions (18/19).

166
JuniorCode#Hooks#Forms

What are hooks?

Hooks is a special JavaScript function that allows you use state and other React features without writing a class. This pattern has been introduced as a new feature in React 16.8 and helped to isolate the stateful logic from the components.

167
MidCode#Hooks#Forms

What rules need to be followed for hooks?

You need to follow two rules in order to use hooks: Call Hooks only at the top level of your react functions: You should always use hooks at the top level of react function before any early returns.

168
MidCode#Hooks#Forms

How to ensure hooks followed the rules in your project?

React team released an ESLint plugin called eslint-plugin-react-hooks that enforces Hook's two rules. It is part of Hooks API. You can add this plugin to your project using the below command.

169
Most AskedJuniorCode#State Management#Forms

What are the differences between Flux and Redux?

The biggest conceptual difference is the data flow itself.

170
Junior#Routing#Forms

What are the benefits of React Router V4?

In React Router v4(version 4), the API is completely about components.

171
MidCode#Components#Forms

Can you describe about componentDidCatch lifecycle method signature?

The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component. The method receives two parameters: error: - The error object which was thrown • info: - An object with a componentStack key contains the information about which component threw the error.

172
MidCode#Forms#Performance

In which scenarios do error boundaries not catch errors?

Inside Event handlers • Asynchronous code using setTimeout or requestAnimationFrame callbacks • During Server side rendering • When errors thrown in the error boundary code itself.

173
JuniorCode#Forms#Performance

What is the behavior of uncaught errors in react 16?

Note: This behavior was introduced in React 16 and continues in React 18/19.

174
JuniorCode#Forms#Performance

What is the proper placement for error boundaries?

The granularity of error boundaries usage is up to the developer based on project needs. You can follow either of these approaches: You can wrap top-level route components to display a generic error message for the entire application.

175
JuniorCode#Components#Forms

What is the benefit of component stack trace from error boundary?

Apart from error messages and javascript stack, React16 will display the component stack trace with file names and line numbers using error boundary concept.

176
JuniorCode#Components#Forms

What are default props?

The defaultProps can be defined as a property on the component to set the default values for the props. These default props are used when props not supplied(i.e., undefined props), but not for null or 0 as props. That means, If you provide null value then it remains null value. It's the same behavior with 0 as well.

177
JuniorCode#Forms#Performance

What is the purpose of displayName class property?

The displayName string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component.

178
JuniorCode#Forms#Performance

What is the browser support for react applications?

React supports all popular browsers, including Internet Explorer 9 and above, although some polyfills are required for older browsers such as IE 9 and IE 10. If you use es5-shim and es5-sham polyfill then it even support old browsers that doesn't support ES5 methods.

179
JuniorCode#Forms#Performance

What is code-splitting?

Code-Splitting is a feature supported by bundlers like Webpack and Browserify which can create multiple bundles that can be dynamically loaded at runtime. The react project supports code splitting via dynamic import() feature.

180
Most AskedJuniorCode#Forms#Performance

What are Keyed Fragments?

The Fragments declared with the explicit syntax may have keys. The general use case is mapping a collection to an array of fragments as below.

181
MidCode#Forms#Performance

Does React support all HTML attributes?

As of React 16, both standard or custom DOM attributes are fully supported. Since React components often take both custom and DOM-related props, React uses the camelCase convention just like the DOM APIs.

182
MidCode#Components#Forms

When component props defaults to true?

If you pass no value for a prop, it defaults to true. This behavior is available so that it matches the behavior of HTML.

183
Junior#Forms#Performance

What is NextJS and major features of it?

Server-rendered by default • Automatic code splitting for faster page loads • Simple client-side routing (page based) • Webpack-based dev environment which supports (HMR).

184
MidCode#Components#Forms

How do you pass an event handler to a component?

You can pass event handlers and other functions as props to child components. The functions can be passed to child component as below.

185
MidCode#Forms#Performance

How to prevent a function from being called multiple times?

If you use an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be achieved in the below possible ways: Throttling: Changes based on a time based frequency • Debouncing: Publish changes after a period of inactivity.

186
MidCode#Forms#Performance

How JSX prevents Injection Attacks?

React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered.

187
MidCode#Forms#Performance

How do you update rendered elements?

You can update UI(represented by rendered element) by passing the newly created element to ReactDOM's render method.

188
MidCode#Components#Forms

How do you say that props are readonly?

When you declare a component as a function or a class, it must never modify its own props.

189
Most AskedJuniorCode#Forms#Performance

What are the conditions to safely use the index as a key?

There are three conditions to make sure, it is safe use the index as a key.

190
MidCode#Forms#Performance

Should keys be globally unique?

The keys used within arrays should be unique among their siblings but they don’t need to be globally unique. i.e, You can use the same keys with two different arrays.

191
Junior#Forms#Performance

What is the popular choice for form handling?

Formik is a form library for react which provides solutions such as validation, keeping track of the visited fields, and handling form submission.

192
Most AskedJunior#State Management#Forms

What are the advantages of formik over redux form library?

The form state is inherently short-term and local, so tracking it in Redux (or any kind of Flux library) is unnecessary • Redux-Form calls your entire top-level Redux reducer multiple times ON EVERY SINGLE KEYSTROKE • Redux-Form is 22.5 kB minified g.

193
Mid#Forms#Performance

Why are you not required to use inheritance?

In React, it is recommended to use composition over inheritance to reuse code between components. Both Props and composition give you all the flexibility you need to customize component behavior and appearance.

194
MidCode#Components#Forms

Can I use web components in react application?

Yes, you can use web components in a react application. Even though many developers won't use this combination, it may require especially if you are using third-party UI components that are written using Web Components.

195
JuniorCode#Forms#Performance

What is dynamic import?

You can achieve code-splitting in your app using dynamic import.

196
JuniorCode#Components#Forms

What are loadable components?

Loadable Components (@loadable/component) is a code-splitting library for React that supports Server-Side Rendering (SSR).

197
Junior#Components#Forms

What is suspense component?

React Suspense is a built-in feature that lets you delay rendering part of the UI until asynchronous work (such as loading a component or fetching data) is ready. While waiting, React shows a fallback UI (loading text, skeleton, spinner, etc.) defined by the nearest Suspense boundary.

198
JuniorCode#Forms#Performance

What is route based code splitting?

One of the best places to do code splitting is with routes. The entire page is going to re-render at once so users are unlikely to interact with other elements in the page at the same time. Due to this, the user experience won't be disturbed.

199
JuniorCode#Forms#Performance

What is the purpose of default value in context?

The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them.

200
JuniorCode#Forms#Performance

What is diffing algorithm?

React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree. The diffing algorithms is generating the minimum number of operations to transform one tree into another. However, the algorithms have a complexity in the order of O(n³) where n is the number of elements in the tree.

201
JuniorCode#Forms#Performance

What are the rules covered by diffing algorithm?

When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements. It covers the below rules during reconciliation algorithm: Elements Of Different Types • DOM Elements Of The Same Type.

202
MidCode#Forms#Performance

When do you need to use refs?

Managing focus, text selection, or media playback • Triggering imperative animations • Integrating with third-party DOM libraries.

203
MidCode#Components#Forms

Must prop be named as render for render props?

Even though the pattern named render props, you don’t have to use a prop named render to use this pattern. i.e, Any prop that is a function that a component uses to know what to render is technically a “render prop”. Lets take an example with the children prop for render props.

204
JuniorCode#Components#Forms

What are the problems of using render props with pure components?

If you create a function inside a render method, it negates the purpose of pure component. Because the shallow prop comparison will always return false for new props, and each render in this case will generate a new value for the render prop. You can solve this issue by defining the render function as instance method.

205
Junior#Forms#Performance

What is windowing technique?

Windowing is a technique that only renders a small subset of your rows at any given time, and can dramatically reduce the time it takes to re-render the components as well as the number of DOM nodes created. If your application renders long lists of data then this technique is recommended. Both react-window and react-virtuali.

206
MidCode#Forms#Performance

How do you print falsy values in JSX?

The falsy values such as false, null, undefined, and true are valid children but they don't render anything. If you still want to display them then you need to convert it to string. Let's take an example on how to convert to a string.

207
Junior#Forms#Performance

What is the typical use case of portals?

React Portals are primarily used to render UI components such as modals, tooltips, dropdowns, hovercards, and notifications outside of their parent component's DOM tree. This helps avoid common CSS issues caused by parent elements, such as: overflow: hidden on parent elements clipping or hiding child elements like modals or tooltips.

208
MidCode#Components#Forms

How do you set default value for uncontrolled component?

In React, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you might want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value.

209
JuniorCode#Forms#Performance

What is your favorite React stack?

Even though the tech stack varies from developer to developer, the most popular stack is used in react boilerplate project code.

210
Most AskedJuniorCode#Forms#Performance

What is the difference between Real DOM and Virtual DOM?

Below are the main differences between Real DOM and Virtual DOM.

211
MidCode#Forms#Performance

How to add Bootstrap to a react application?

Bootstrap can be added to your React app in a three possible ways: Using the Bootstrap CDN • Bootstrap as Dependency • React Bootstrap Package.

212
MidCode#Forms#Performance

Can you list down top websites or applications using react as front end framework?

Facebook • Uber • Instagram • WhatsApp.

213
JuniorCode#Forms#Performance

Is it recommended to use CSS In JS technique in React?

React does not have any opinion about how styles are defined but if you are a beginner then good starting point is to define your styles in a separate \*.css file as usual and refer to them using className. This functionality is not part of React but came from third-party libraries.

214
MidCode#Components#Hooks

Do I need to rewrite all my class components with hooks?

No. But you can try Hooks in a few components(or new components) without rewriting any existing code. Because there are no plans to remove classes in ReactJS.

215
Most AskedJuniorCode#Hooks#Forms

What is useEffect hook? How to fetch data with React Hooks?

The useEffect hook is a React Hook that lets you perform side effects in function components. Side effects are operations that interact with the outside world or system and aren't directly related to rendering UI — such as fetching data, setting up subscriptions, timers, manually manipulating the DOM, etc.

216
MidCode#Hooks#Forms

Is Hooks cover all use cases for classes?

Hooks doesn't cover all use cases of classes but there is a plan to add them soon. Currently there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet.

217
JuniorCode#Hooks#Forms

What is the stable release for hooks support?

React includes a stable implementation of React Hooks in 16.8 release for below packages.

218
MidCode#Hooks#Forms

Why do we use array destructuring (square brackets notation) in useState?

When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that updates the value. Using [0] and [1] to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.

219
JuniorCode#Hooks#Forms

What are the sources used for introducing hooks?

Previous experiments with functional APIs in the react-future repository • Community experiments with render prop APIs such as Reactions Component • State variables and state cells in DisplayScript • Subscriptions in Rx.

220
MidCode#Components#Forms

How do you access imperative API of web components?

Web Components often expose an imperative API to implement its functions. You will need to use a ref to interact with the DOM node directly if you want to access imperative API of a web component.

221
JuniorCode#Forms#Performance

What is formik?

Formik is a small react form library that helps you with the three major problems: Getting values in and out of form state • Validation and error messages • Handling form submission.

222
Most AskedJuniorCode#State Management#Forms

What are typical middleware choices for handling asynchronous calls in Redux?

Some of the popular middleware choices for handling asynchronous calls in Redux eco system are Redux Thunk, Redux Promise, Redux Saga.

223
MidCode#Forms#Performance

Do browsers understand JSX code?

No, browsers can't understand JSX code. You need a transpiler to convert your JSX to regular Javascript that browsers can understand. The most widely used transpiler right now is Babel.

224
MidCode#Forms#Performance

Describe about data flow in react?

React implements one-way reactive data flow using props which reduce boilerplate and is easier to understand than traditional two-way data binding.

225
JuniorCode#Forms#Performance

What is MobX?

MobX is a simple, scalable and battle tested state management solution for applying functional reactive programming (TFRP). For ReactJS application, you need to install below packages.

226
Most AskedJuniorCode#State Management#Forms

What are the differences between Redux and MobX?

Below are the main differences between Redux and MobX.

227
MidCode#Forms#Performance

Should I learn ES6 before learning ReactJS?

No, you don’t have to learn es2015/es6 to learn react. But you may find many resources or React ecosystem uses ES6 extensively. Let's see some of the frequently used ES6 features: Destructuring: To get props and use them in a component.

228
Most AskedMidCode#Forms#Performance

Explain concurrent rendering with an example

Concurrent rendering in React 18 lets React prepare UI updates in a non-blocking way. This means React can pause low-priority rendering work, handle urgent updates first (like typing or clicking), and then continue rendering.

229
JuniorCode#Forms#Performance

What is the difference between async mode and concurrent mode?

Both refers the same thing. Previously concurrent Mode being referred to as "Async Mode" by React team. The name has been changed to highlight React’s ability to perform work on different priority levels. So it avoids the confusion from other approaches to Async Rendering.

230
JuniorCode#Hooks#Forms

What is the purpose of eslint plugin for hooks?

The ESLint plugin enforces rules of Hooks to avoid bugs. It assumes that any function starting with ”use” and a capital letter right after it is a Hook. In particular, the rule enforces that: Calls to Hooks are either inside a PascalCase function (assumed to be a component) or another useSomething function (assumed to be a custom Hook).

231
JuniorCode#Forms#Performance

What is the difference between Imperative and Declarative in React?

Imagine a simple UI component, such as a "Like" button. When you tap it, it turns blue if it was previously grey, and grey if it was previously blue.

232
JuniorCode#Forms#Performance

What are the benefits of using TypeScript with ReactJS?

It is possible to use latest JavaScript features • Use of interfaces for complex type definitions • IDEs such as VS Code was made for TypeScript • Avoid bugs with the ease of readability and Validation.

233
Most AskedMidCode#State Management#Forms

How do you make sure that user remains authenticated on page refresh while using Context API State Management?

When a user logs in and reload, to persist the state generally we add the load user action in the useEffect hooks in the main App.js. While using Redux, loadUser action can be easily accessed.

234
Junior#Forms#Performance

What are the benefits of new JSX transform?

It is possible to use JSX without importing React packages • The compiled output might improve the bundle si.

235
MidCode#Forms#Performance

How is the new JSX transform different from old transform??

The new JSX transform doesn’t require React to be in scope. i.e, You don't need to import React package for simple scenarios.

236
Most AskedJuniorCode#Components#Forms

What are React Server components?

React Server Component is a way to write React component that gets rendered in the server-side with the purpose of improving React app performance. These components allow us to load components from the backend.

237
JuniorCode#Forms#Performance

What is prop drilling?

Prop Drilling is the process by which you pass data from one component of the React Component tree to another by going through other components that do not need the data but only help in passing it around.

238
JuniorCode#Hooks#Forms

What is the difference between useState and useRef hook?

useState causes components to re-render after state updates whereas useRef doesn’t cause a component to re-render when the value or state changes • useState allows us to update the state inside components.

239
JuniorCode#Components#Forms

What is a wrapper component?

A wrapper in React is a component that wraps or surrounds another component or group of components. It can be used for a variety of purposes such as adding additional functionality, styling, or layout to the wrapped components.

240
Most AskedJuniorCode#Hooks#Forms

What are the differences between useEffect and useLayoutEffect hooks?

Both useEffect and useLayoutEffect share identical signatures, but differ in when they execute relative to DOM mutation and browser painting.

241
JuniorCode#Components#Forms

What are the differences between Functional and Class Components?

There are two different ways to create components in ReactJS. The main differences are listed down as below.

242
JuniorCode#Forms#Performance

What is strict mode in React?

React.StrictMode is a useful component for highlighting potential problems in an application. Just like Fragment, StrictMode does not render any extra DOM elements. It activates additional checks and warnings for its descendants. These checks apply for development mode only.

243
JuniorCode#Forms#Performance

What is the benefit of strict mode?

The StrictMode will be helpful in the below cases: To find the bugs caused by impure rendering where the components will re-render twice • To find the bugs caused by missing cleanup of effects where the components will re-run effects one more extra time • Identifying components with unsafe lifecycle methods.

244
MidCode#Forms#Performance

Why does strict mode render twice in React?

StrictMode renders components twice in development mode(not production) in order to detect any problems with your code and warn you about those problems. This is used to detect accidental side effects in the render phase. If you used create-react-app development tool then it automatically enables StrictMode by default.

245
JuniorCode#Forms#Performance

What are the rules of JSX?

The below 3 rules needs to be followed while using JSX in a react application.

246
JuniorCode#Forms#Performance

What is the reason behind multiple JSX tags to be wrapped?

Behind the scenes, JSX is transformed into plain javascript objects. It is not possible to return two or more objects from a function without wrapping into an array. This is the reason you can't simply return two or more JSX tags from a function without wrapping them into a single parent tag or a Fragment.

247
MidCode#Forms#Performance

How do you prevent mutating array variables?

The preexisting variables outside of the function scope including state, props and context leads to a mutation and they result in unpredictable bugs during the rendering stage. The below points should be taken care while working with arrays variables.

248
JuniorCode#Forms#Performance

What are capture phase events?

The onClickCapture React event is helpful to catch all the events of child elements irrespective of event propagation logic or even if the events propagation stopped. This is useful if you need to log every click events for analytics purpose.

249
MidCode#Forms#Performance

How does React updates screen in an application?

React updates UI in three steps: Triggering or initiating a render: The component is going to triggered for render in two ways.

250
MidCode#Forms#Performance

How does React batch multiple state updates?

React prevents component from re-rendering for each and every state update by grouping multiple state updates within an event handler. This strategy improves the application performance and this process known as batching.

251
MidCode#Forms#Performance

Is it possible to prevent automatic batching?

Yes, it is possible to prevent automatic batching default behavior. There might be cases where you need to re-render your component after each state update or updating one state depends on another state variable.

252
JuniorCode#Forms#Performance

What is React hydration?

React hydration is used to add client-side JavaScript interactivity to pre-rendered static HTML generated by the server. It is used only for server-side rendering(SSR) to enhance the initial rendering time and make it SEO friendly application. This hydration acts as a bridge to reduce the gap between server side and client-side rendering.

253
MidCode#Forms#Performance

How do you update objects inside state?

You cannot update the objects which exists in the state directly. Instead, you should create a fresh new object (or copy from the existing object) and update the latest state using the newly created object. Eventhough JavaScript objects are mutable, you need to treat objects inside state as read-only while updating the state.

254
MidCode#Forms#Performance

How do you update nested objects inside state?

You cannot simply use spread syntax for all kinds of objects inside state. Because spread syntax is shallow and it copies properties for one level deep only. If the object has nested object structure, UI doesn't work as expected with regular JavaScript nested property mutation.

255
MidCode#Forms#Performance

How do you update arrays inside state?

Eventhough arrays in JavaScript are mutable in nature, you need to treat them as immutable while storing them in a state. That means, similar to objects, the arrays cannot be updated directly inside state. Instead, you need to create a copy of the existing array and then set the state to use newly copied array.

256
MidCode#Forms#Performance

How do you use immer library for state updates?

Immer library enforces the immutability of state based on copy-on-write mechanism. It uses JavaScript proxy to keep track of updates to immutable states. Immer has 3 main states as below: Current state: It refers to actual state • Draft state: All new changes will be applied to this state.

257
JuniorCode#Forms#Performance

What are the benefits of preventing the direct state mutations?

Preventing direct state mutations is a core principle in React because React relies on shallow reference equality checks (prevProps !== nextProps or prevState !== nextState) to determine whether a component should re-render.

258
JuniorCode#Forms#Performance

What are the preferred and non-preferred array operations for updating the state?

The below table represent preferred and non-preferred array operations for updating the component state.

259
MidCode#Components#Forms

What will happen by defining nested function components?

Technically it is possible to write nested function components but it is not suggested to write nested function definitions. Because it leads to unexpected bugs and performance issues.

260
MidCode#Forms#Performance

Can I use keys for non-list items?

Keys are primarily used for rendering list items but they are not just for list items. You can also use them React to distinguish components. By default, React uses order of the components in.

261
JuniorCode#State Management#Forms

What are the guidelines to be followed for writing reducers?

There are two guidelines to be taken care while writing reducers in your code.

Part 9: React Hooks Deep Dive (262 - 316)

146 Questions
262
Mid#Hooks

How does ReactJS work behind the scenes?

ReactJS is a powerful JavaScript library for building user interfaces. While it appears simple on the surface, React performs a lot of complex operations behind the scenes to efficiently update the UI. Here's an overview of how it works internally.

263
MidCode#Hooks

How is useReducer Different from useState?

There are notable differences between useState and useReducer hooks.

264
JuniorCode#Hooks

What is useContext? What are the steps to follow for useContext?

The useContext hook is a built-in React Hook that lets you access the value of a context inside a functional component without needing to wrap it in a component.

265
Junior#Hooks

What are the use cases of useContext hook?

Theme Customization.

266
MidCode#CLI#Components

When to use client and server components?

You can efficiently build nextjs application if you are aware about which part of the application needs to use client components and which other parts needs to use server components. The common cases of both client and server components are listed below.

267
JuniorCode#Hooks#Routing

What are the differences between page router and app router in nextjs?

Next.js provides two different routing systems: the Page Router (traditional) and the App Router (introduced in Next.js 13). The App Router is built on React Server Components and offers more powerful features for modern web applications.

268
MidCode#Hooks

Can you describe the useMemo() Hook?

The useMemo() Hook in React is used to optimize performance by caching the result of an expensive calculation between re-renders. It takes a calculate function and a list of dependencies, re-computing the value only when one of the dependencies has changed.

269
MidCode#Components#Hooks

Can Hooks be used in class components?

No, Hooks cannot be used inside class components. They are specially designed for function components. This is because hooks depend on the sequence in which they are called during a component’s render, something that's only guaranteed in functional components.

270
JuniorCode#Hooks

What is an updater function? Should an updater function be used in all cases?

An updater function is a form of setState where you pass a function instead of a direct value. This function receives the previous state as an argument and returns the next state.

271
MidCode#Hooks

Can useState take a function as an initial value?

Yes, useState accepts an initialization function (called Lazy Initial State).

272
JuniorCode#Hooks

What types of values can useState hold?

The useState hook accepts different types of values.: Primitives: number, string, boolean • Arrays • Objects • Functions.

273
MidCode#Hooks

What happens if you call useState conditionally?

As per rules of React Hooks, hooks must be called unconditionally. For example, if you conditionally call it.

274
MidCode#Hooks#Async & Promises

Is useState Synchronous or Asynchronous?

The useState hook is synchronous, but state updates are asynchronous. When you call useState(), it runs synchronously and returns the state variable and setter function as tuple. This happens immediately during rendering.

275
SeniorCode#Hooks

Can you explain how useState works internally?

React’s hooks, including useState, rely on some internal machinery that keeps track of state per component and per hook call during rendering. Here's a simplified explanation of the internal mechanics.

276
JuniorCode#Hooks

What is useReducer? Why do you use useReducer?

The useReducer hook is a React hook used to manage complex state logic inside functional components. It is conceptually similar to Redux. i.e, Instead of directly updating state like with useState, you dispatch an action to a reducer function, and the reducer returns the new state.

277
MidCode#Hooks

How does useReducer works? Explain with an example

The useReducer hooks works similarly to Redux, where: You define a reducer function to handle state transitions • You dispatch actions to update the state.

278
MidCode#Hooks

Can you combine **useReducer** with **useContext**?

Yes, it's common to combine useReducer with useContext to build a lightweight state management system similar to Redux.

279
MidCode#Hooks#State Management

Can you dispatch multiple actions in a row with useReducer?

Yes, you can dispatch multiple actions in a row using useReducer but not directly in one call. You'd have to call dispatch multiple times or create a composite action in your reducer that performs multiple updates based on the action type.

280
Mid#Hooks#Async & Promises

Is dispatch from useReducer asynchronous and does it update state immediately?

The dispatch function returned by useReducer is not asynchronous — it is a synchronous function call. When you call dispatch(action), React synchronously invokes your reducer with the current state and the action, computes the new state, and schedules a re-render.

281
MidCode#Hooks

How does useContext works? Explain with an example

The useContext hook can be used for authentication state management across multiple components and pages in a React application.

282
MidCode#Components#Hooks

Can You Use Multiple Contexts in One Component?

Yes, it is possible. You can use multiple contexts inside the same component by calling useContext multiple times, once for each context.

283
MidCode#Hooks

What's a common pitfall when using useContext with objects?

A common pitfall when using useContext with objects is triggering unnecessary re-renders across all consuming components — even when only part of the context value changes.

284
MidCode#Hooks

What would the context value be for no matching provider?

When a component calls useContext(SomeContext) but no matching is present higher up in the component tree, the default value passed to React.createContext(defaultValue) is returned.

285
Most AskedMidCode#Hooks#Data Structures

How do reactive dependencies in the useEffect dependency array affect its execution behavior?

The useEffect hook accepts an optional dependencies argument that accepts an array of reactive values. The dependency array determines when the effect runs. i.e, It makes useEffect reactive to changes in specified values.

286
Most AskedMidCode#Hooks

When and how often does React invoke the setup and cleanup functions inside a useEffect hook?

Setup Function Execution (useEffect).

287
Most AskedMidCode#Hooks#Async & Promises

What happens if you return a Promise from useEffect??

You should NOT return a Promise from useEffect. React expects the function passed to useEffect to return either nothing (undefined) or a cleanup function (synchronous function). i.e, It does not expect or handle a returned Promise.

288
Most AskedMidCode#Components#Hooks

Can you have multiple useEffect hooks in a single component?

Yes, multiple useEffect hooks are allowed and recommended when you want to separate concerns.

289
Most AskedMidCode#Hooks

How to prevent infinite loops with useEffect?

Infinite loops happen when the effect updates state that’s listed in its own dependency array, which causes the effect to re-run, updating state again and so on.

290
Junior#Hooks

What are the usecases of useLayoutEffect?

You need to use useLayoutEffect when your effect must run before the browser paints, such as: Reading layout measurements (e.g., element si.

291
MidCode#Hooks#SSR & Hydration

How does useLayoutEffect work during server-side rendering (SSR)?

The useLayoutEffect hook does not run on the server, because there is no DOM. React issues a warning in server environments like Next.js if useLayoutEffect is used directly.

292
MidCode#Hooks

What happens if you use useLayoutEffect for non-layout logic?

Using useLayoutEffect for logic unrelated to layout or visual DOM changes (such as logging, data fetching, or analytics) is not recommended. It can lead to performance issues or even unexpected behavior.

293
MidCode#Hooks

How does useLayoutEffect cause layout thrashing?

The useLayoutEffect can cause layout thrashing when you repeatedly read and write to the DOM in ways that force the browser to recalculate layout multiple times per frame. This is because useLayoutEffect runs before the browser paints, these reflows happen synchronously, blocking rendering and degrading performance.

294
MidCode#Hooks

How Do You Use useRef to Access a DOM Element in React? Give an example.

The useRef hook is commonly used in React to directly reference and interact with DOM elements — like focusing an input, scrolling to a section, or controlling media elements.

295
MidCode#Hooks

Can you use useRef to persist values across renders??

Yes, you can use useRef to persist values across renders in React. Unlike useState, changing .current does not cause re-renders, but the value is preserved across renders.

296
MidCode#Hooks

Can useRef be used to store previous values?

Yes, useRef is a common pattern when you want to compare current and previous props or state without causing re-renders.

297
MidCode#Hooks

Is it possible to access a ref in the render method?

Yes, you can access a ref in the render method, but what you get from it depends on how you're using the ref and when in the component lifecycle you're rendering.

298
JuniorCode#Hooks

What are the common usecases of useRef hook?

Some of the common cases are: Automatically focus an input when a component mounts • Scroll to a specific element • Measure element dimensions (offsetWidth, clientHeight) • Control video/audio playback.

299
JuniorCode#Hooks

What is useImperativeHandle Hook? Give an example.

useImperativeHandle is a React Hook that allows a child component to expose custom functions or properties to its parent component, when using ref.

300
MidCode#Hooks

When should you use useImperativeHandle?

The useImperativeHandler hook will be used in below cases: You want to expose imperative methods from a child component • Custom input controls exposing focus, clear, or validate methods • Modal components exposing open() and close() methods • Scroll containers exposing scrollToTop() or scrollToBottom() methods.

301
MidCode#Hooks

Is that possible to use useImperativeHandle without forwardRef?

No. useImperativeHandle only works when the component is wrapped in forwardRef. It's the combination that allows parent components to use a ref on a function component.

302
Mid#Hooks

How is useMemo different from useCallback?

The following table compares both useMemo and useCallback.

303
Mid#Components#Hooks

Does useMemo prevent re-rendering of child components?

The useMemo hook does not directly prevent re-rendering of child components. Its main purpose is to memoize expensive computations. However, it can indirectly prevent child re-renders when memoizing a complex object or array passed as props to a child wrapped in React.memo, preserving referential equality between renders.

304
JuniorCode#Hooks

What is useCallback and why is it used?

The useCallback is a React Hook used to memoize callback functions across renders. It prevents unnecessary re-renders of optimized child components (React.memo) that rely on reference equality of function props.

305
JuniorCode#Hooks

What are Custom React Hooks, and How Can You Develop One?

Custom Hooks in React are JavaScript functions that allow you to extract and reuse component logic using React’s built-in Hooks like useState, useEffect, etc.

306
Most AskedSeniorCode#Hooks

How does React Fiber works? Explain in detail.

React Fiber is the complete rewrite of React's core reconciliation algorithm (introduced in React 16). Its primary purpose is to enable incremental rendering—the ability to split rendering work into chunks and spread it out over multiple frames.

307
JuniorCode#Hooks

What is the useId hook and when should you use it?

The useId hook is a React hook introduced in React 18 that generates unique IDs that are stable across server and client renders. It's primarily used for accessibility attributes like linking form labels to inputs.

308
Junior#Hooks

What is the useDeferredValue hook?

The useDeferredValue hook is used to defer updating a part of the UI to keep other parts responsive. It accepts a value and returns a "deferred" version of that value that may lag behind. This is useful for optimizing search inputs and heavy list filtering.

309
JuniorCode#Hooks

What is the useTransition hook and how does it differ from useDeferredValue?

The useTransition hook allows you to mark certain state updates as non-urgent transitions, keeping the UI responsive during expensive re-renders. It returns a isPending flag and a startTransition function.

310
JuniorCode#Hooks

What is the useSyncExternalStore hook?

The useSyncExternalStore hook is designed to subscribe to external stores (non-React state sources) in a way that's compatible with concurrent rendering. It's primarily used by library authors for state management libraries.

311
JuniorCode#Hooks

What is the useInsertionEffect hook?

The useInsertionEffect hook is designed for CSS-in-JS library authors to inject styles into the DOM before any layout effects run. It fires synchronously before DOM mutations.

312
Most AskedMidCode#Components#Hooks

How do you share state logic between components using custom hooks?

Custom hooks allow you to extract and share stateful logic between components without changing their hierarchy. The state itself is not shared—each component using the hook gets its own isolated state.

313
JuniorCode#Hooks

What is the useDebugValue hook?

The useDebugValue hook is used to display a label for custom hooks in React DevTools. It helps developers debug custom hooks by showing meaningful information.

314
Most AskedMidCode#Hooks

How do you handle cleanup in useEffect?

The cleanup function in useEffect is used to clean up side effects before the component unmounts or before the effect runs again. This prevents memory leaks, stale data, and unexpected behavior.

315
Most AskedJuniorCode#Hooks

What are the differences between useEffect and useEvent (experimental)?

useEvent is an experimental hook (not yet stable in React) designed to solve the problem of creating stable event handlers that always access the latest props and state without causing re-renders or needing to be in dependency arrays.

316
JuniorCode#Hooks

What are the best practices for using React Hooks?

Following best practices ensures your hooks are predictable, maintainable, and bug-free.

317
JuniorCode#Hooks

What is Concurrent Rendering? (Legacy)

The Concurrent rendering makes React apps to be more responsive by rendering component trees without blocking the main UI thread. It allows React to interrupt a long-running render to handle a high-priority event.

318
MidCode#Hooks

Why should we not update the state directly?

If you try to update the state directly then it won't re-render the component.

319
JuniorCode#Hooks

What is the purpose of callback function as an argument of setState()?

The callback function provided as the second argument to setState is executed after the state has been updated and the component has re-rendered. Because setState() is asynchronous, you cannot reliably perform actions that require the updated state immediately after calling setState.

320
MidCode#Hooks

How to bind methods or event handlers in JSX callbacks?

Binding in Constructor: In JavaScript classes, the methods are not bound by default.

321
MidCode#Hooks

How to pass a parameter to an event handler or callback?

You can use an arrow function to wrap around an event handler and pass parameters.

322
JuniorCode#Hooks

What is the use of refs?

The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need a direct access to the DOM element or an instance of a component.

323
MidCode#Hooks

How to create refs?

This is a recently added approach.

324
JuniorCode#Hooks

What are forward refs?

Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child.

325
MidCode#Hooks

Which is preferred option with in callback refs and findDOMNode()?

It is preferred to use callback refs over findDOMNode() API. Because findDOMNode() prevents certain improvements in React in the future.

326
MidCode#Hooks

Why are String Refs legacy?

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like ref={'textInput'}, and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have below issues, and are considered legacy. String refs were removed in React v16.

327
Junior#Components#Hooks

What are the different phases of component lifecycle?

The component lifecycle has three distinct lifecycle phases: Mounting: The component is ready to mount in the browser DOM.

328
JuniorCode#Hooks#Lifecycle

What are the lifecycle methods of React?

Before React 16.3: componentWillMount: Executed before rendering and is used for App level configuration in your root component • componentDidMount: Executed after first rendering and here all AJAX requests, DOM or state updates, and set up event listeners should occur.

329
MidCode#Components#Hooks

How to create props proxy for HOC component?

You can add/edit props passed to the component using props proxy pattern like this.

330
JuniorCode#Hooks

What is context?

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

331
JuniorCode#Components#Hooks

What is the purpose of using super constructor with props argument?

A child class constructor cannot make use of this reference until the super() method has been called. The same applies to ES6 sub-classes as well. The main reason for passing props parameter to super() call is to access this.props in your child constructors.

332
MidCode#Hooks

How to set state with a dynamic key name?

If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names.

333
MidCode#Components#Hooks

What would be the common mistake of function being called every time the component renders?

You need to make sure that function is not being called while passing the function as a parameter.

334
JuniorCode#Hooks

What are error boundaries in React v16?

Note: Error boundaries were introduced in React 16 and remain valid in current React versions (18/19).

335
MidCode#Hooks

How are error boundaries handled in React v15?

⚠️ LEGACY: This question is only relevant for historical context. React v15 is extremely outdated (released in 2016).

336
JuniorCode#Hooks

What is the purpose of render method of react-dom?

This method is used to render a React element into the DOM in the supplied container and return a reference to the component. If the React element was previously rendered into container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes.

337
Mid#Hooks

What will happen if you use setState() in constructor?

When you use setState(), then apart from assigning to the object state React also re-renders the component and all its children. You would get error like this: Can only update a mounted or mounting component. So we need to use this.state to initialize state directly in the constructor.

338
Mid#Components#Hooks

Is it good to use setState() in componentWillMount() method?

⚠️ DEPRECATED: componentWillMount() has been removed in React 17+. This question is only relevant for legacy React applications.

339
Mid#Components#Hooks

What will happen if you use props in initial state?

If the props on the component are changed without the component being refreshed, the new prop value will never be displayed because the constructor function will never update the current state of the component. The initialization only occurs once during mounting.

340
MidCode#Hooks#TypeScript

How you use decorators in React?

You can decorate your class components, which is the same as passing the component into a function. Decorators are flexible and readable way of modifying component functionality.

341
JuniorCode#Hooks

What is CRA and its benefits?

⚠️ OUTDATED: Create React App (CRA) is no longer actively maintained and is not recommended for new projects as of 2024+.

342
JuniorCode#Hooks#Lifecycle

What is the lifecycle methods order in mounting?

The lifecycle methods are called in the following order when an instance of a component is being created and inserted into the DOM.

343
Junior#Hooks#Lifecycle

What are the lifecycle methods going to be deprecated in React v16?

⚠️ FULLY DEPRECATED: These lifecycle methods have been deprecated and removed from React 17+.

344
JuniorCode#Components#Hooks

What is the purpose of getDerivedStateFromProps() lifecycle method?

The new static getDerivedStateFromProps() lifecycle method is invoked after a component is instantiated as well as before it is re-rendered. It can return an object to update state, or null to indicate that the new props do not require any state updates.

345
JuniorCode#Hooks#Lifecycle

What is the purpose of getSnapshotBeforeUpdate() lifecycle method?

The new getSnapshotBeforeUpdate() lifecycle method is called right before DOM updates. The return value from this method will be passed as the third parameter to componentDidUpdate().

346
JuniorCode#Components#Hooks

What is the recommended way for naming components?

It is recommended to name the component by reference instead of using displayName.

347
JuniorCode#Components#Hooks

What is the recommended ordering of methods in component class?

Recommended ordering of methods from mounting to render stage: static methods • constructor() • getChildContext() • componentWillMount().

348
Mid#Hooks

Why we need to pass a function to setState()?

The reason behind for this is that setState() is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after setState() is called. That means you should not rely on the current state when calling setState() since you can't be sure what that state will be.

349
JuniorCode#Hooks

Why is isMounted() an anti-pattern and what is the proper solution?

The primary use case for isMounted() is to avoid calling setState() after a component has been unmounted, because it will emit a warning.

350
JuniorCode#Hooks

What is the difference between constructor and getInitialState?

constructor: Used in ES6 class components (class MyComponent extends React.Component) to initialize local component state by assigning an object • getInitialState: Used in legacy React.createClass() components to return the initial state object.

351
MidCode#Components#Hooks

Can you force a component to re-render without calling setState?

By default, when your component's state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().

352
JuniorCode#Components#Hooks

What is the difference between super() and super(props) in React using ES6 classes?

When you want to access this.props in constructor() then you should pass props to super() method.

353
JuniorCode#Hooks

What is the difference between setState() and replaceState() methods?

When you use setState() the current and previous states are merged. replaceState() throws out the current state, and replaces it with only what you provide. Usually setState() is used unless you really need to remove all previous keys for some reason. You can also set state to false/null in setState() instead of using replaceState().

354
MidCode#Hooks

How to listen to state changes?

The componentDidUpdate lifecycle method will be called when state changes. You can compare provided state and props values with current state and props to determine if something meaningful changed.

355
JuniorCode#Hooks#Data Structures

What is the recommended approach of removing an array element in React state?

The better approach is to use Array.prototype.filter() method.

356
MidCode#Hooks

Is it possible to use React without rendering HTML?

It is possible. Below are the possible options.

357
JuniorCode#Hooks

What are the possible ways of updating objects in state?

Calling setState() with an object to merge with state.

358
JuniorCode#Hooks

What are the approaches to include polyfills in your create-react-app?

Manual import from core-js.

359
MidCode#Hooks#HTTP & REST APIs

How to use https instead of http in create-react-app?

You just need to use HTTPS=true configuration. You can edit your package.json scripts section.

360
MidCode#Hooks

How to avoid using relative path imports in create-react-app?

Create a file called .env in the project root and write the import path.

361
MidCode#Components#Hooks

How to update a component every second?

You need to use setInterval() to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.

362
MidCode#Components#Hooks

Why is a component constructor called only once?

React's reconciliation algorithm assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it's the same component as before, so reuses the previous instance rather than creating a new one.

363
MidCode#Hooks

How to define constants in React?

You can use ES7 static field to define constant.

364
MidCode#CLI#Hooks

How to programmatically trigger click event in React?

You could use the ref prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.

365
MidCode#Components#Hooks

How to make AJAX call and in which component lifecycle methods should I make an AJAX call?

You can use AJAX libraries such as Axios, jQuery AJAX, and the browser built-in fetch. You should fetch data in the componentDidMount() lifecycle method. This is so you can use setState() to update your component when the data is retrieved.

366
JuniorCode#Components#Hooks

What are render props?

Render Props is a technique for sharing code/logic between components using a prop whose value is a function that returns a React element. Instead of duplicating stateful logic in every component that needs it, a "provider" component encapsulates the logic and delegates what to render to its caller via this function prop.

367
MidCode#Hooks

How to dispatch an action on load?

You can dispatch an action in componentDidMount() method and in render() method you can verify the data.

368
Most AskedMidCode#Hooks#State Management

How to use connect() from React Redux?

You need to follow two steps to use your store in your container: Use mapStateToProps(): It maps the state variables from your store to the props that you specify • Connect the above props to your container: The object returned by the mapStateToProps function is connected to the container.

369
Most AskedJuniorCode#Hooks#State Management

Whats the purpose of at symbol in the Redux connect decorator?

The @ symbol is in fact a JavaScript expression used to signify decorators. Decorators make it possible to annotate and modify classes and properties at design time.

370
MidCode#Hooks#TypeScript

How to use TypeScript in create-react-app application?

Starting from react-scripts@3.3.0+ releases onwards, you can now optionally start a new app from a template by appending --template [template-name] to the creation command. If you don't select a template, it will create your project with base template.

371
MidCode#Hooks

Does the statics object work with ES6 classes in React?

No, statics only works with React.createClass().

372
MidCode#Hooks

Why are inline ref callbacks or functions not recommended?

If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one.

373
JuniorCode#Hooks

What are HOC factory implementations?

Props Proxy (PP) and • Inheritance Inversion (II).

374
Junior#Hooks

How to use class field declarations syntax in React classes?

React Class Components can be made much more concise using class field declarations. You can initialize state and class properties directly as class fields without a constructor.

375
MidCode#Hooks

Why do you not need error boundaries for event handlers?

Error boundaries do not catch errors inside event handlers.

376
JuniorCode#Hooks

What is the difference between try catch block and error boundaries?

Try catch block works with imperative code whereas error boundaries are meant for declarative code to render on the screen.

377
JuniorCode#Components#Hooks

What is the required method to be defined for a class component?

The render() method is the only required method in a class component. i.e, All methods other than render method are optional for a class component.

378
JuniorCode#Hooks

What are the possible return types of render method?

React elements: Elements that instruct React to render a DOM node • Arrays and fragments: Return multiple elements to render as Arrays and Fragments to wrap multiple elements • Portals: Render children into a different DOM subtree • String and numbers: Render both Strings and Numbers as text nodes in the DOM.

379
JuniorCode#Hooks

What is the main purpose of constructor?

In React class components, the constructor is mainly used for two purposes: Initializing Local State: Assigning an object directly to this.state (without calling setState).

380
MidCode#Components#Hooks

Is it mandatory to define constructor for React component?

No, it is not mandatory. If your component does not initialize state and does not bind methods, you do not need to implement a constructor.

381
MidCode#Components#Hooks

Why should not call setState in componentWillUnmount?

You should not call setState() in componentWillUnmount() because once a component instance is unmounted, it will never be mounted again.

382
JuniorCode#Hooks

What is the purpose of getDerivedStateFromError?

This lifecycle method is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return a value to update state.

383
JuniorCode#Components#Hooks

What is the methods order when component re-rendered?

An update can be caused by changes to props or state. The below methods are called in the following order when a component is being re-rendered.

384
JuniorCode#Hooks

What are the methods invoked during error handling?

Below methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.

385
JuniorCode#Components#Hooks

What is the purpose of unmountComponentAtNode method?

This method is available from react-dom package and it removes a mounted React component from the DOM and clean up its event handlers and state. If no component was mounted in the container, calling this function does nothing. Returns true if a component was unmounted and false if there was no component to unmount.

386
JuniorCode#Hooks

What are the limitations with HOCs?

Don’t use HOCs inside the render method.

387
MidCode#Hooks

How to debug forwardRefs in DevTools?

React.forwardRef accepts a render function as parameter and DevTools uses this function to determine what to display for the ref forwarding component.

388
Mid#Hooks

Is it good to use arrow functions in render methods?

Yes, you can use arrow functions in render methods. It is often the easiest way to pass parameters to callback functions. However, each render creates a new function instance, so if passed to memoized child components, optimize using useCallback or instance methods to prevent unnecessary child re-renders.

389
MidCode#Hooks

How do you say that state updates are merged?

When you call setState() in the component, React merges the object you provide into the current state.

390
MidCode#Hooks

How do you pass arguments to an event handler?

During iterations or loops, it is common to pass an extra parameter to an event handler. This can be achieved through arrow functions or bind method.

391
MidCode#Components#Hooks

How to prevent component from rendering?

You can prevent component from rendering by returning null based on specific condition. This way it can conditionally render component.

392
MidCode#Hooks

Give an example on How to use context?

Context is designed to share data that can be considered global for a tree of React components.

393
MidCode#Hooks

How do you use contextType?

ContextType is used to consume the context object. The contextType property can be used in two ways: contextType as property of class.

394
JuniorCode#Hooks

What is a consumer?

A Consumer is a React component that subscribes to context changes. It requires a function as a child which receives current context value as argument and returns a react node. The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree.

395
MidCode#Hooks#Forms

How do you solve performance corner cases while using context?

The context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider’s parent re-renders.

396
JuniorCode#Hooks

What is the purpose of forward ref in HOCs?

Refs will not get passed through because ref is not a prop. It is handled differently by React just like key. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component. In this case, you can use Forward Ref API.

397
MidCode#Components#Hooks

Is ref argument available for all functions or class components?

Regular function or class components don’t receive the ref argument, and ref is not available in props either. The second ref argument only exists when you define a component with React.forwardRef call.

398
MidCode#Components#Hooks

Why do you need additional care for component libraries while using forward refs?

When you start using forwardRef in a component library, you should treat it as a breaking change and release a new major version of your library. This is because your library likely has a different behavior such as what refs get assigned to, and what types are exported.

399
MidCode#Components#Hooks

How to create react class components without ES6?

If you don’t use ES6 then you may need to use the create-react-class module instead. For default props, you need to define getDefaultProps() as a function on the passed object. Whereas for initial state, you have to provide a separate getInitialState method that returns the initial state.

400
MidCode#Hooks

Is it possible to use react without JSX?

Yes, JSX is not mandatory for using React. Actually it is convenient when you don’t want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React.createElement(component, props...children).

401
JuniorCode#Components#Hooks

How do you create HOC using render props?

You can implement most higher-order components (HOC) using a regular component with a render prop. For example, if you would prefer to have a withMouse HOC instead of a Mouse component, you could easily create one using a regular Mouse with a render prop.

402
JuniorCode#Hooks

What is react scripts?

The react-scripts package is a set of scripts from the create-react-app starter pack which helps you kick off projects without configuring. The react-scripts start command sets up the development environment and starts a server, as well as hot module reloading.

403
Junior#Hooks

What are the features of create react app?

Below are the list of some of the features provided by create react app.

404
JuniorCode#Hooks

What is the purpose of renderToNodeStream method?

The ReactDOMServer#renderToNodeStream method is used to generate HTML on the server and send the markup down on the initial request for faster page loads. It also helps search engines to crawl your pages easily for SEO purposes. Note: Remember this method is not available in the browser but only server.

405
Most AskedMidCode#Hooks#State Management

How do you get redux scaffolding using create-react-app?

Redux team has provided official redux+js or redux+typescript templates for create-react-app project. The generated project setup includes: Redux Toolkit and React-Redux dependencies • Create and configure Redux store • React-Redux Provider passing the store to React components.

406
JuniorCode#Hooks#GraphQL

What is state mutation and how to prevent it?

State mutation happens when you try to update the state of a component without actually using setState function. This can happen when you are trying to do some computations using a state variable and unknowingly save the result in the same state variable.

407
JuniorCode#Hooks

What are React Mixins?

⚠️ DEPRECATED: Mixins are considered legacy and should not be used in modern React applications.