https://www.freecodecamp.org/news/react-interview-questions-and-answers/
React is an open-source front-end JavaScript library for creating user interfaces. It is declarative, efficient, and flexible, and it adheres to the component-based approach, which allows us to create reusable UI components.
Developer primarily use React to create Single Page Applications and the library focuses solely on the view layer of MVC. It is also extremely fast.
React has many features that set it apart, but here are a few highlights:
We can create a React app from scratch by initalizing a project and installing all dependencies. But the easiest way is by using create-react-app via the command below:
xxxxxxxxxx11npx create-react-app my-appNote: my-app is the name of the application we are creating, but you can change it to any name of your choice.
You can read more on how to get started with React in this article.
The term "DOM" stands for Document Object Model and refers to the representation of the entire user interface of a web application as a tree data structure.
We have two types of DOM which are the Virual DOM and the Real DOM.
Here are some of the advantages and disadvantages of React:
JavaScript XML is abbreviated as JSX. JSX enables and simplifies the creation of HTML in React, resulting in more readable and understandable markup.
For example:
xxxxxxxxxx71const App = () => {2 return (3 <div>4 <h1>Hello World</h1>5 </div>6 )7}You can read more about JSX in React in this article.
JSX is not a valid JavaScript code, and there is no built-in implementation that allows the browser to read and understand it. We need to transpile the code from JSX into valid JavaScript code that the browser can understand, and we use Babel, a JavaScript compiler/transpiler, to accomplish this.
Note: create-react-app uses Babel internally for the JSX to JavaScript conversion, but you can also set up your own babel configuration using Webpack.
You can read more about JSX in React in this article.
A component is a self-contained, reusable code block that divides the user interface into smaller pieces rather than building the entire UI in a single file.
There are two kinds of components in React: functional and class components.
Class components are ES6 classes that return JSX and necessitate the use of React extensions. Because it was not possible to use state inside functional components in earlier versions of React (16.8), functional components were only used for rendering UI.
Example:
xxxxxxxxxx101import React, { Component } from 'react'2export default class App extends Component {3 render() {4 return (5 <div>6 <h1>Hello World</h1>7 </div>8 )9 }10}Read more about React components and the types of components in this article.
A JavaScript/ES6 function that returns a React element is referred to as a functional component (JSX).
Since the introduction of React Hooks, we have been able to use states in functional components, which has led to many people adopting them due to their cleaner syntax.
Example:
xxxxxxxxxx91import React from 'react'2const App = () => {3 return (4 <div>5 <h1>Hello World</h1>6 </div>7 )8}9export default App;Read more about React components and the types of components in this article.
| Functional Components | Class Components |
|---|---|
| A functional component is a JavaScript/ES6 function that takes an argument, props, and returns JSX. | You must extend from React in order to use a class component. Create a component and a render function that returns a React element. |
| There is no render method used in functional components. | It must have the render() method returning JSX |
| Functional components run from top to bottom and cannot be kept alive once the function is returned. | The class component is instantiated, and various life cycle methods are kept alive and are run and invoked depending on the phase of the class component. |
| They are also known as stateless components because they only accept data and display it in some form, and they are primarily responsible for UI rendering. | They are also referred to as Stateful components because they implement logic and state. |
| React lifecycle methods cannot be used in functional components. | React lifecycle methods can be used inside class components. |
| Hooks like useState() were created to be used in functional components to make them Stateful. | It requires different syntax inside a class component to implement hooks. |
| Constructors are not used. | Constructor are used as it needs to store state. |
There are 3 ways to style a react application with CSS:
Read more on how to style a React application in this article.
Render() is used in the class component to return the HTML that will be displayed in the component. It is used to read props and state and return our JSX code to our app's root component.
Props are also referred to as properties. They are used to transfer data from one component to the next (parent component to child component). They are typically used to render dynamically generated data.
Note: A child component can never send props to a parent component since this flow is unidirectional (parent to child).
Example:
xxxxxxxxxx101function App({name, hobby}) {2 return (3 <div>4 <h1>My name is {name}.</h1>5 <p>My hobby is {hobby}.</p>6 </div>7 );8}910export default App;Read more about how props works in React here.
State is a built-in React Object that is used to create and manage data within our components. It differs from props in that it is used to store data rather than pass data.
State is mutable (data can change) and accessible through this.state().
Example:
xxxxxxxxxx161class App extends React.Component {2 constructor(props) {3 super(props);4 this.state = {5 name: "John Doe"6 };7 }89 render() {10 return (11 <div>12 <h1>My name is {this.state.name}</h1>13 </div>14 );15 }16}It is important to know that when we update a state directly it won’t re-render the component – meaning we don’t get to see the update.
If we want it to re-render, then we have to use the setState() method which updates the component’s state object and re-reders the component.
Example:
xxxxxxxxxx221class App extends React.Component {2 constructor(props) {3 super(props);4 this.state = {5 name: "John Doe"6 };7 }8 changeName = () => {9 this.setState({name: "Jane Doe"});10 }11 render() {12 return (13 <div>14 <h1>My {this.state.name}</h1>15 <button16 type="button"17 onClick={this.changeName}18 >Change Name</button>19 </div>20 );21 }22}You can learn more here.
State and props are JavaScript objects with distinct functions.
Props are used to transfer data from the parent component to the child component, whereas state is a local data storage that is only available to the component and cannot be shared with other components.
In React, an event is an action that can be triggered by a user action or a system generated event. Mouse clicks, web page loading, key press, window resizes, scrolls, and other interactions are examples of events.
Example:
xxxxxxxxxx51// For class component2<button type="button" onClick={this.changeName} >Change Name</button>34// For function component5<button type="button" onClick={changeName} >Change Name</button>Events in React are handled similarly to DOM elements. One difference we must consider is the naming of our events, which are named in camelCase rather than lowercase.
Example:
xxxxxxxxxx161class App extends Component {2 constructor(props) {3 super(props);4 this.handleClick = this.handleClick.bind(this);5 }6 handleClick() {7 console.log('This button was Clicked');8 }9 render() {10 return (11 <div>12 <button onClick={this.handleClick}>Click Me</button>13 </div>14 );15 }16}xxxxxxxxxx111const App = () => {2 const handleClick = () => {3 console.log('Click happened');4 };5 return (6 <div>7 <button onClick={handleClick}>Click Me</button>8 </div>9 );10};11export default App;In functional components, we can do this:
xxxxxxxxxx111const App = () => {2 const handleClick = (name) => {3 console.log(`My name is ${name}`);4 };5 return (6 <div>7 <button onClick={() => handleClick('John Doe')}>Click Me</button>8 </div>9 );10};11export default App;And in class components we can do this:
xxxxxxxxxx131class App extends React.Component {2 call(name) {3 console.log(`My name is ${name}`);4 }5 render() {6 return (7 <button onClick= {this.call.bind(this,"John Doe")}>8 Click the button!9 </button>10 );11 }12}13export default App;Redux is a popular open-source JavaScript library for managing and centralizing application state. It is commonly used with React or any other view-library.
Learn more about redux here.
React hooks were added in v16.8 to allow us to use state and other React features without having to write a class.
They do not operate within classes, but rather assist us in hooking into React state and lifecycle features from function components.
The React team first introduced React Hooks to the world in late October 2018, during React Conf, and then in early February 2019, with React v16. 8.0.
The useState Hook is a store that enables the use of state variables in functional components. You can pass the initial state to this function, and it will return a variable containing the current state value (not necessarily the initial state) and another function to update this value.
Example:
xxxxxxxxxx111import React, { useState } from 'react';23const App = () => {4 const [count, setCount] = useState(0);56 return (7 <div>8 // ...9 </div>10 );11}The useEffect Hook allows you to perform side effects in your components like data fetching, direct DOM updates, timers like setTimeout(), and much more.
This hook accepts two arguments: the callback and the dependencies, which allow you to control when the side effect is executed.
Note: The second argument is optional.
Example:
xxxxxxxxxx201import React, {useState, useEffect} from 'react';23const App = () => {4 const [loading, setLoading] = useState(false);5 6 useEffect(() => {7 setLoading(true);8 setTimeout(() => {9 setLoading(false);10 }, 2000);11 }, []);12 13 return(14 <div>15 // ...16 </div>17 )18}1920export default App;The useMemo() hook is used in functional components to memoize expensive functions so that they are only called when a set input changes rather than every render.
Example:
xxxxxxxxxx11const result = useMemo(() => expensivesunction(input), [input]);This is similar to the useCallback hook, which is used to optimize the rendering behavior of your React function components. useMemo is used to memoize expensive functions so that they do not have to be called on every render.
The useRefs() hook, also known as the References hook, is used to store mutable values that do not require re-rendering when they are updated. It is also used to store a reference to a specific React element or component, which is useful when we need DOM measurements or to directly add methods to the components.
When we need to do the following, we use useRefs:
Example:
xxxxxxxxxx171import React, {useEffect, useRef} from 'react';23const App = () => {4 const inputRef = useRef(null)5 6 useEffect(()=>{7 inputElRef.current.focus()8 }, [])9 10 return(11 <div>12 <input type="text" ref={inputRef} />13 </div>14 )15}1617export default App;Custom Hooks are a JavaScript function that you write to allow you to share logic across multiple components, which was previously impossible with React components.
If you're interested in learning how this works, here is a step by step guide to help you build your own Custom React Hook.
Context is intended to share "global" data for a tree of React components by allowing data to be passed down and used (consumed) in whatever component we require in our React app without the use of props. It allows us to share data (state) more easily across our components.
Read more about React Context in this guide.
React router is a standard library used in React applications to handle routing and allow navigation between views of various components.
Installing this library into your React project is as simple as typing the following command into your terminal:
xxxxxxxxxx11npm install – -save react-router-domxxxxxxxxxx231用户访问 URL2↓3服务器返回 HTML4↓5浏览器解析 HTML / CSS6↓7下载 JS(bundle)8↓9React 启动10↓11(CSR 或 SSR 分叉)12↓13Virtual DOM → Fiber14↓15Reconciliation(diff)16↓17Commit(更新 DOM)18↓19页面可交互20↓21用户操作 → State 更新22↓23Re-render → 局部更新
下面我们按阶段逐个拆解术语。
发生了什么
/xxxxxxxxxx11SPA 的本质:HTML 只加载一次
📌 术语出现:
这里是第一个分叉点
xxxxxxxxxx21服务器 → 返回空壳 HTML2<script src="bundle.js"></script>
特点
📌 涉及术语
xxxxxxxxxx21服务器 → 返回完整 HTML2<h1>Home</h1>
特点
📌 涉及术语
发生了什么
xxxxxxxxxx21HTML:我已经有了2React:我来接管它
📌 面试标准回答
Hydration 是把服务端生成的 HTML 变成可交互的 React 应用的过程。
⚠️ 易错点
Fiber 是什么
📌 Fiber 带来的能力
xxxxxxxxxx11Fiber = 可被暂停和恢复的渲染单元
发生了什么
📌 相关术语
⚠️ 面试高频追问
为什么 key 不能用 index?
📌 可被打断(Concurrent)
📌 一句话
Render 负责算,Commit 负责改
此时:
📌 出现术语
xxxxxxxxxx11setCount(c => c + 1)
Re-render 是什么
📌 常见误区 ❌ re-render = 页面重绘 ✅ re-render = 重新计算 UI
解决什么问题
xxxxxxxxxx31startTransition(() => {2setList(filterItems())3})
📌 含义
用户访问 SPA → CSR 或 SSR 返回 HTML → Hydration 让页面可交互 → React 使用 Fiber 进行渲染 → Reconciliation 计算差异 → Commit 更新 DOM → State 更新触发 Re-render → Concurrent 保证流畅度