This page aims to aggregate multiple basic React interview questions in a succinct and unopinionated manner. I try my best to adhere as closely to React source documentation as possible but if you see anywhere that information can be better summarized please let me know.
Please Note Before Reading:
These answers are meant as quick references/ light refreshers and are not comprehensive explanations or tutorials. One main purpose of this page is to redirect users to great sources containing answers and further readings for said questions. As such, I have included my citation links throughout most questions. Please refer to those for a more thorough explanation.
This sheet also only covers a basic overview, it doesn’t go in-depth of the inner workings or practical applications of React that may very well be required for more experienced positions.
Table of Contents
These questions show a basic grasp of what React is and how it works:
- What is React?
- By Facebook
2. What are React’s Key Features?
- Virtual DOM
- Unidirectional Data Flow
- Server-Side Rendering
3. What is JSX?
- Babel compiles JSX into
- Cleaner code with JSX expressions
- (B) Safer code as the usage of JSX prevents XSS attacks¹
- Manipulating the actual DOM is expensive
- Virtual DOM: React makes a virtual representation of the actual DOM in memory
- Expected changes are first reflected in an updated version of the Virtual DOM. The updated virtual DOM is compared with its previous version using React’s ‘diffing’ algorithm to determine how to best update the real DOM
- Further Reading: Reconciliation, Inside Fiber: in-depth overview of the new reconciliation algorithm in React, Virtual Dom is Pure Overhead
- Component: an independent reusable piece of the UI
- Class Component: Component implemented using ES6 Classes extending
- Function Component: Component implemented by a JS function that takes a props argument and returns a React element
2. How do Class components compare with Function components?
- With React Hooks, class components are replaceable with function components for the majority of use cases¹
- In the past, stateful and life cycle logic could only be incorporated in class components
Function Component Disadvantages
- There are no Hook equivalents yet for the uncommon life cycles:
- Older third-party libraries might not be compatible with hooks yet
Class Components Disadvantages
- Classes add unnecessary confusion for the sake of syntactic sugar²
- Classes lead to a bulky hierarchy tree, especially during code reuse, which results in performance decreases and difficulty testing³
- Class lifecycle methods split up related pieces of code⁴
- Further reading: How Are Function Components Different from Classes?
- props is immutable by the receiving Component
- Updates to either trigger a re-render
4. What causes a component to update?
- A re-render of the parent which may entail new Props
forceUpdate()(and that it should be avoided!)
setState()schedules an update to a component’s
stateobject. When state changes, the component responds by re-rendering.
- Calls to
setState()are asynchronous and may be batched¹ ²
- Updates to
this.statedo not reflect the new value immediately after calling
- Because of its asynchronous nature, Calling
setState()by passing an object containing the current state value can result in unexpected behaviour
setState()a function rather than an object allows you to access the current state value, avoiding potential unexpected behaviour caused asynchronicity
- 3 phases: Mounting, Updating, Unmounting
render→ DOM update →
render→ DOM update →
- (B) inclusion of
7. How can I prevent unnecessary re-rendering?
React.PureComponent: Components created off of this class do a shallow comparison with the upcoming
stateand re-render if there are changes
React.Memo: Higher-order component that works like
React.PureComponentbut used for function components
shouldComponentUpdate: Lifecycle method that takes in the next
stateand returns a boolean indicating if the component should rerender
- Identify bottlenecks: Profiling components in Chrome via Chrome Performance Tab or DevTools Profiler
- Virtualize long lists — only render list nodes as you need them
- Avoiding unnecessary re-renders (See the previous question)
- Using a Production Build
- Refs provide access to DOM nodes or React elements created in the
- In the past, refs were limited only to class components but now can be accessed in function components via the
- Managing focus, text selection, or media playback.
- Triggering imperative animations.
- Integration with third-party DOM libraries.
- Keys are constant strings values that uniquely identifies a list item among its siblings
- Keys help React identify which items have changed, are added, or are removed.
- Keys are necessary because reconciling list elements differences without them is highly inefficient¹
11. What are Controlled and Uncontrolled components in React?
- Both are ways to implement form controls in React
- Controlled: form data is handled by a React component
- Uncontrolled: form data is handled by the DOM itself
- Controlled components are the recommended way to implement forms
- Uncontrolled components are an option when converting legacy code bases to React, or integration with a non-React library¹
- The content between the opening and closing tags of a component is passed as the children attribute of props:
props.childrencan be string literals, HTML syntax, JS expressions, and JS functions
- Components become Error Boundaries if they define either:
- Error Boundaries are usually defined once and used throughout the application by wrapping around other components like catch blocks
14. Talk to me about handling events in React. Where does
SyntheticEvent fit into the picture?
- Handling events on React elements is similar to that of regular DOM elements except React sports several syntactic differences¹
- Syntax Difference 1: React events are named using camelCase, rather than lowercase.
- Syntax Difference 2: With JSX you pass a function as the event handler, rather than a string.
- React elements receive synthetic events on handling
SyntheticEvent: A React cross-browser wrapper object around the browser’s native event
SyntheticEventallow events to function identically across browsers
thisis the context of a function and takes on dynamic values depending on how the function is invoked
- When the function used as an event handler as part of a class,
thisis not bound and as a result is undefined, causing an exception to be thrown if this.state or this.props is accessed
- Resolution 1:
thiscan be explicitly bound using the
- Resolution 2: Because arrow functions take the
thisvalue of their enclosing lexical scope,
thiscan be bound with the use of arrow functions
16. What are the common approaches to reusing code in React?
- Higher-order component: A function that takes a React component and transforms it into another component by enriching it with reusable functionality
- Common in third-party libraries, a prevalent example is React Redux’s
- Easily compose a component by chaining multiple HoC’s
- Disadvantage: Poor readability when chaining many HoC’s resulting in Wrapper Hell
- Disadvantage: Wrapper hell can result in a nested tree and difficulty debugging
- Render Props: A pattern where a component uses a prop (a function) that dictates its render logic rather than implementing its own.
- Prevalent example is React-Router
- Disadvantage: Can potentially be verbose as render logic needs to be passed into JSX
- Disadvantage: Incorrect implementation can lead to memory issues¹
- Part of React 16.8 hook update, and allows you to reuse stateful logic without restructuring your component hierarchy
- In most cases, custom hooks are sufficient in replacing render props and HoCs and reduce the amount of nesting needed²
- Allow you to avoid wrapper hell/multiple layers of abstraction that can come with Render Props and HoCs
- Disadvantage: Hooks cannot be used inside classes³
- All 3 are ways of tackling Cross-Cutting Concerns: ¹ ² ³
- Common follow up is to implement a simple HoC, Render Prop, or custom hook
- Further Readings 1: Higher-order components vs Render Props
- Further Reading 2: Comparison: HOCs vs Render Props vs Hooks
- A common misconception is that fetching data in the
constructoravoids an additional rendering step compared to
- Reality: Fetching data in the
constructoroffers no performance improvements over
- Data won’t be loaded if the async request in
constructorcompletes after the component mounts
- Best practices are to avoid side effects in
- In the
constructor, the state should be initialized and
setState()should not be called²
- (B) Data fetching via async calls can be managed using the
- (B) React Suspense is a potential alternative to fetch data in the future⁴
1. What are React Hooks?
- New feature in React 16.8
- Allows function components to use state and other previous class-only features
- Backwards compatible and optional
- Hooks allow for simply reuse of stateful logic without layering abstractions like HoCs and Render Props (See the question about code reuse)
- Fully opt-in and backward compatible
- Hooks make complicated components easier to understand by grouping related code together into functions
- Hooks allow you to avoid Class components which introduce unnecessary complications
3. What is the useState hook?
useStateis a Hook that lets you add React state to function components
useStatelike all Hooks is a function
- Argument: the initial state
- Returns: Pair containing the current state and a function to update it.
4. What is the
useEffectlets you perform side effects in function components
useEffectis triggered after a render
useEffectis like the combination of
- Arguments: function to be called, and an array for React to check for changes in order to render
5. What is the
useReduceris an alternative to
useStatethat is used when there is complex state logic that that involves multiple sub-values or when the next state depends on the previous one
- 3 Arguments: Reducer function, initial State Object, and a function to initialize the state lazily
- Reducer function takes the current state and action variable and returns the next state
- Returns: a pair containing the current state, and a dispatch function for dispatching an action.
- Works similarly to Redux
6. What are custom hooks?
- (See the question about code reuse, specifically the section about custom hooks)
- Hooks avoid a lot of the overhead that is present with classes such as the creation of instances and binding of events
- Hooks result in smaller component trees because it avoids the nesting present in HoCs and render props resulting in less work for React to do.
1. What is Redux?
- Redux is a library for managing application state
- Redux is a solution for global state management, allowing you to pass data without the need to pass props through every level (aka props drilling)
- Inspired by Facebook’s flux architecture
2. What are the main constituents of Redux?
typeproperty to indicate what type of action is being performed
- Actions are dispatched to the central store using
- Actions are usually created by Action Creator functions, which given some input generates the corresponding action.
- Reducers are functions that take an Action and a current state and returns the resulting state
- Reducers must be pure functions and have no side effects
- The Store is the central object that maintains and updates the application state
- The Store also handles the registration and unregistering of listeners
- Redux revolves around strict unidirectional data flow
- First: an Action is dispatched to the store via
- Second: Redux determine the resultant state by calling a Reducer function
- Third: The root reducer combines the output of multiple reducers into a single state tree
- Fourth: The Store saves the new state tree and notifies listeners that are registered
- A Selector is a function that takes in the Redux store state and returns the derived desired data from that state.
- Selectors allow the Redux store state to be as minimal as possible by computing data off of the state
- Selectors allow for better separation of concern by keeping components free from state transformation logic
- Selector computations can be memoized to prevent additional computation
- Selectors can also be composed and reused across an application
- Redux Toolkit: an official opinionated Redux toolset to get you up and running quickly with Redux without having the worry about the boilerplate. Comes with premade functions and utilities that help easily configure the store and create actions and reducers.
- Redux Toolkit comes baked with widely used Redux Addons:
- Redux Thunk — Middleware for async logic
- Reselect — Easily create memoized selectors
6. What is Context API?
- Like Redux, Context API is a solution for state management
- Context is an official feature as part of React 16.3
Context has 3 main parts:
- A Context object is created using
- A Provider is a component that triggers all descendant consumers of itself to rerender when there is a change to its value
- A Consumer is a component that subscribes to context changes
7. How do I solve global state management with Hooks?
- By passing the
useContexthook a context object, function components can hook onto changes to the nearest corresponding Provider and will rerender when there is an update
- Function components can alternatively still use Consumers to subscribe to Context updates, although
useContextis arguably more readable¹
6. How does Context API compare to Redux and when would you use one over the other?
- Set up for Redux requires more additional work than Context as Context is built into React.
- For most smaller use cases simpler use cases, Context should be sufficient
- Redux allows access to middleware, which triggers a function after an action is dispatched
- Redux provides access to the robust debugging tool Redux DevTools, that allow you to time travel and see changes made to your store step by step
- Further Readings: Context Api vs Redux, Context vs Redux, Redux not dead yet, You Might Not Need Redux
What made you choose to use React?
What are some scenarios/reasons you wouldn’t choose React?
What are some things you are looking forward to in the future of React?
What are recent additions that you like about React?
What don’t you like about React?
What is something you’ve built in React?
- What are the challenges you faced building it?
- How did you overcome said challenges?
What is an interesting bug you encountered while working in React?
Tell me about your testing process at your current project
I’ve aggregated my questions from these great sources, please give them a read for more in-depth answers and insight: