Learn React by asking questions. React interview questions.

Vlad Antsitovich
14 min readFeb 3, 2022

This article contains the most popular and relevant interview questions. I hope you will use it to learn something new or fill some gaps.

Before we get started I highly recommend you to check out the best React Course ever: Epic React by Kent C. Dodds to become a PRO in React.

This article will keep updated.

What is React?

React is a JavaScript library for building user interfaces (UI). It’s not a framework like Angular or Vue.

React gives us advantages like: we don’t need to touch the DOM at all; build apps like lego blocks by using component approach.

React DOM is a complimentary library to React which glues React to the browser DOM.

What is JSX?

It’s a syntax extension to JavaScript. JSX produces React “elements” and Bable compiles it down to React.createElement.

Basically JSX just provides syntactic sugar for the React.createElement(component, props, ...children)function.

React.createElement() essentially it creates an object like this:

Element in React

Unlike browser DOM elements, React elements are plain objects and are cheap to create. React DOM takes care of updating the DOM to match the React elements.

What are React elements and React components?

First, let’s understand what is DOM, DOM Node, and DOM Element:

  • DOM or Document Object Model represents all page content as objects that can be modified. The document object is the main “entry point” to the page. We can change or create anything on the page using it. Everything in HTML, even comments, becomes a part of the DOM.
  • DOM Node represents every object located within a document. In addition, every kind of DOM node is represented by an interface based on Node. These include Attr, CharacterData (which Text, Comment, CDATASection and ProcessingInstruction are all based on), and DocumentType. A DOM document is a hierarchical collection of nodes. Nodes have types, the element type being one of them. The element is represented by a tag in the HTML document.
  • DOM Element is based on DOM Node. It’s a node of a specific type — element (Node.ELEMENT_NODE). A DOM element is something like a DIV, HTML, BODY element on a page.

React Elements are plain objects describing a component instance or DOM node and its desired properties.

React uses a particular type of object, called an element, which describes what has to be shown on the screen. These immutable objects are much simpler compared to the components and their instances and contain only the information that is strictly needed to represent the interface.

Check out: Why Do React Elements Have a $$typeof Property?

React Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. Components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React Elements describing what should appear on the screen.

React Component is just a composition of React Elements.

Benefits of Components:

  • Breakdown and isolate UI into easier to reason parts
  • Easy to test
  • Code Re-use

More:

React use declarative or imperative concept?

React is declarative. Being declarative means that you just describe what you want to be displayed on the screen at any point in time and React takes care of the communications with the browser.

Imperative code instructs JavaScript on how it should perform each step. With declarative code, we tell JavaScript what we want to be done, and let JavaScript take care of performing the steps.

More:

What are Composition and Inheritance?

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components.

Facebook uses React in thousands of components and hasn’t found any use cases where can recommend creating component inheritance hierarchies.

Learn more about Composition and Inheritance:

What are Uncontrolled components and Controlled components?

Uncontrolled components are like regular HTML form inputs for which you will not be able to manage the value yourself but instead, the DOM will take care of handling the value and you can get this value by using a React ref.

Controlled component is a React component that controls the values of input elements in a form by using the component state.

In React we prefer to use controlled components, it gives us more flexibility.

What are Higher-Order Components?

Higher-order component is a function that takes a component and returns a new component.

Also checkput React Render Props

Learn more about Higher Order Components:

What is DOM and Virtual DOM? Virtual DOM vs Shadow DOM

The Document Object Model (DOM) is a popular concept followed in client-side development. It’s a fundamental technique that is both cross-platform and language-independent.

React renders JSX components to the Browser DOM, but keeps a copy of the actual DOM to itself. This copy is the Virtual DOM. We can think of it as the twin brother of the real or Browser DOM.

React uses two Virtual DOMs to render the user interface. One of them is used to store the current state of the objects and the other to store the previous state of the objects. Whenever the virtual DOM gets updated, react compares the two Virtual DOMs and gets to know about which virtual DOM objects were updated. After knowing which objects were updated, react renders only those objects inside the real DOM instead of rendering the complete real DOM. This way, with the use of virtual DOM, react solves the problem of inefficient updating.

Differences between Virtual DOM and Shadow DOM?

Shadow DOM and Virtual DOM are not related.

The Shadow DOM is a browser technology for encapsulating the implementation of web components. Using the shadow DOM, you can hide the implementation details of a web component from the regular DOM tree.

The Virtual DOM is used to efficiently redraw UIs whereas the Shadow DOM encapsulates(hides) the implementation and provides isolated scope of custom web components.

More:

What is dangerouslySetInnerHTML attribute?

Basically dangerouslySetInnerHTML is nothing but a replacement of innerHTML in React and should be used with care. Although the name suggests danger in its use, taking the necessary measure by using a well-developed sanitizer ensures the code is clean and does not run unexpected scripts when rendered within the React node.

How does React work with events? What is a synthetic event in React?

React defines these synthetic events according to the W3C spec, so you don’t need to worry about cross-browser compatibility. React events do not work exactly the same as native events. See the SyntheticEvent reference guide to learn more.

When using React, you generally don’t need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.

A couple more interesting things to know about events in React are that synthetic events are reused and that there is a single global handler. The first concept means that we cannot store a synthetic event and reuse it later because it becomes null right after the action. This technique is very good in terms of performance, but it can be problematic if we want to store the event inside the state of the component for some reason. To solve this problem, React gives us a persistent method on the synthetic events, which we can call to make the event persistent so that we can store it and retrieve it later.

The second very interesting implementation detail is again about performance, and it is to do with the way React attaches the event handlers to the DOM.

Whenever we use the on an attribute, we are describing to React the behavior we want to achieve, but the library does not attach the actual event handler to the underlying DOM nodes.

What it does instead attaches a single event handler to the root element, which listens to all the events, thanks to event bubbling. When an event we are interested in is fired by the browser, React calls the handler on the specific components on its behalf. This technique is called event delegation and is used for memory and speed optimization.

What are state and props?

Props are variables passed to it by its parent component. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component.

State on the other hand is still variables but directly initialized and managed by the component. And the state can be initialized by props.

The state is an updatable structure that is used to contain data or information about the component and can change over time. Props are read-only.

Why we should not mutate props inside components?

Note: React is pretty flexible but it has a single strict rule: All React components must act like pure functions with respect to their props.

What is React.Fragment?

Fragments let you group a list of children without adding extra nodes to the DOM.

We use <React.Fragment> instead of <></> because they doesn’t support key or attributes.

What is React Strict Mode?

StrictMode is a tool for highlighting potential problems in an application. Like Fragment, StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.

Note: Strict mode checks are run in development mode only; they do not impact the production build.

StrictMode currently helps with:

Additional functionality will be added with future releases of React.

What is React Context?

Basically, React Context API solves one big problem: props drilling. Props drilling is basically a situation when the same data is being sent at almost every level due to requirements in the final level. Here is a diagram to demonstrate it better.

A good way to use Context API in a small part of an application (components, widgets).

If we need a global state and a lot of actions it’s better to use State Library (like Redux) cuz it contains performance optimization.

Learn more about React Context:

React Hooks

Hooks are functions. They let you use state and other React features without writing a class.

With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.

Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods.

Hooks let you use more of React’s features without classes.

Hooks != Lifecycles

Hooks also have a few rules:

  1. Use hooks only inside other hooks or in components
  2. A custom hook should start with use
  3. No conditions and loops
  4. Custom hook should return stable links of any function (see example below)
Custom hook with stable links

Why we can’t use hooks conditionally?

Because hooks must call in a specific order. Internally, hooks rely on the order in which other hooks are called. If we add some conditions to call the hook, then this order is violated and we get unpredictable behavior.

More:

useEffect

useEffect is the built-in hook that allows us to run some code after React renders (and re-renders) a component to the DOM.

We don’t need to think about component lifecycle when we use effects, we should think about state synchronization. The question is not “When does this effect run” the question is “With which state does this effect synchronize with”:

useEffect state synchronize

useEffect is an async function, it means useEffect calls after React updating the DOM and then asynchronous later it's going to call useEffect callbacks one at a time in the order in which they were called.

What is the difference between useEffect and useLayoutEffect?

useEffect runs after the browser paints the screen

useLayoutEffect runs before paints screen.

Learn more about useEffect hook:

What is refs?

Every time when we need to interact with DOM nodes we should use refs.

There are a few good use cases for refs:

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

But you can use useRef hook not only for working with DOM nodes, you can use this hook anytime you want to maintain a reference to something and you want to make changes to that without triggraing re-render. So in these cases you can use useRef hook instead of useState .

Note: Changes in useRef object not triggering a re-render.

More:

Re-rendering, performance and optimization in React

React is really fast and in many cases, we don’t need to worry about re-rendering, performance, and optimization, but if our application becomes bigger (I mean UI and logic) and we need to think about how it’s can impact on User Experience (UX).

Magic number: 16 milliseconds (60 frames per second) this time for our JavaScript to execute any part of code to avoid any bad User Experience.

Without knowing how React works we can’t understand how we can improve our React application.

Lifecycle of a React app

React app has 4 phases:

  1. Render — create elements (React.createElement)
  2. Reconciliation — compare pervious elements with new element
  3. Commit — update the DOM (if needed)
  4. State Change — whats trigger the re-render phase

Lifecycle of a React component

  1. Mounting
  2. Updating
  3. Unmounting

Don’t be confused with life cycles and lifecycle methods

Lifecycle methods are special methods built into React, used to operate on components throughout their duration in the DOM.

More:

When does React re-render components? And how we can optimise our React App?

Before we get started let’s understand some importent concepts.

Rendering — is not updating the DOM. Component can render without any visible changes in the DOM.

Re-render can be caused due to any of the reasons:

  1. Update in State
  2. Update in prop
  3. Re-rendering of the parent component
  4. A component using useContext and the context value changes.

Performance Optimization is a big topic so use these sources to build a strong knowledge:

What is React.memo?

React.memo is a higher order component that you can use to ensure functional components only re-render when the props change (much like PureComponent for class components). It’s a tool you can use for improving performance in your React applications.

Do we have something like shouldComponentUpdate in a functional component?

A functional component will re-render every time the parent renders it, no matter if the props have changed or not.

However, using the React.memo high order component it is actually possible for functional components to get the same shouldComponentUpdate check which is used in PureComponent

Also it’ good to know that React.memo accepts custom compsison funciton:

Why do we use a key prop?

Keys help React identify which items have changed, are added, or are removed. It’s allow us to

React’s key prop gives you the ability to control component instances. Each time React renders your components, it's calling your functions to retrieve the new React elements that it uses to update the DOM. If you return the same element types, it keeps those components/DOM nodes around, even if all the props changed.

Note: One important thing we need to understand about key prop, everytime when key prop changes it will unmount and mount component again. And if key prop stays the same it will not trigger a re-render for component.

Can we get the key prop inside the component?

No. Keys serve as a hint to React but they don’t get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name.

Why we don’t use an array index as a key? Or we can?

We can use an index of an array as a key only if we are sure that the array will not be modified or items will add at the end of the list.

More:

What is Reconciliation in React?

Reconciliation is responsible for maintaining the tree of elements when components get re-render. React creates a new tree of elements every time the render function is called. And to be efficient we need a way to tell what’s different between the two trees (new tree and previous tree). Reconciliation houses the diffing algorithm that determines what parts of the tree need to be replaced.

Reconciliation is the process through which React updates the Browser DOM. The reconciliation process makes React work faster.

More:

What is React Fiber?

React Fiber — the core algorithm behind React. React Fiber is the new reconciliation algorithm in React 16.

Introduced from React 16, Fiber Reconciler is the new reconciliation algorithm in React. The term Fiber refers to React’s data structure (or) architecture, and originates from ‘fiber’ — a representation of a node of the DOM tree.

The main goals of the Fiber reconciler are incremental rendering, better or smoother rendering of UI animations and gestures, and responsiveness of the user interactions.

It’s also increases the suitability of the React library to create animations, layouts, and gestures.

Through its feature of incremental rendering, React Fiber lets developers split rendering work into smaller chunks and distribute it over multiple frames. This allows users to essentially control the “priority” of work.

For example, React Fiber could help you prioritise functions that originate from user actions while delaying logic of less-important background or offscreen functions to avoid frame rate drops.

More:

Code splitting

Learn more about code splitting:

What is Error Boundary?

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

Note: I recommend to use react-error-boundary library instead of creating your own component. Check out more about this library in Kent C. Dodds article.

Patterns in React

Compound Components

Compound components is a pattern where higher level components are composed using smaller components, and you retain access to all the semantic elements of the higher level component.

Example of Compound components:

Learn more about Compound Components:

To learn more patterns in React check out:

--

--