https://www.freecodecamp.org/news/react-interview-questions-and-answers/
English Answer: React is an open-source front-end JavaScript library for creating user interfaces. It is declarative, efficient, and flexible, and it adheres to a component-based approach, which allows us to create reusable UI components. Developers primarily use React to create Single Page Applications (SPAs) as it focuses solely on the view layer of MVC.
中文翻译: React 是一个用于构建用户界面的开源前端 JavaScript 库。它是声明式的、高效且灵活的,并遵循组件化开发模式,允许我们创建可复用的 UI 组件。开发者主要使用 React 来创建单页面应用 (SPA),因为它专注于 MVC 架构中的视图 (View) 层。
English Answer:
中文翻译:
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.
It allows us to write HTML-like structures directly in JavaScript code. It is a syntactic sugar that React transforms into standard JavaScript objects (React Elements). Browsers cannot read JSX directly, so it must be compiled by tools like Babel or SWC into React.createElement() calls.
For example:
1const App = () => {2 return (3 <div>4 <h1>Hello World</h1>5 </div>6 )7}JSX 代表 JavaScript XML。它允许我们在 JavaScript 代码中直接编写类似 HTML 的结构。它是一种语法糖,React 会将其转换为标准的 JavaScript 对象(React 元素)。浏览器无法直接读取 JSX,因此必须通过 Babel 或 SWC 等工具将其编译为 React.createElement() 调用。
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.
English Answer (Optimized): A component is a self-contained, reusable code block that divides the UI into smaller pieces.
React.Component. They require a render() method and handle lifecycle methods explicitly.中文翻译: 组件是独立且可复用的代码块,用于将 UI 拆分为更小的单元。
React.Component 的 ES6 类。它们必须包含 render() 方法,并显式处理生命周期。React.Component and must implement a render() method.React.Component 的 ES6 类,且必须实现 render() 方法。useState Hook. Class components manage state via the this.state object and update it using this.setState().useState Hook 来管理状态。类组件则通过 this.state 对象管理状态,并使用 this.setState() 进行更新。componentDidMount, componentDidUpdate, and componentWillUnmount. Functional components use the useEffect Hook to handle all these lifecycle events in a unified way.componentDidMount(挂载)、componentDidUpdate(更新)和 componentWillUnmount(卸载)。函数组件则使用 useEffect Hook 以统一的方式处理这些生命周期事件。this keyword, often needing to bind event handlers in the constructor. Functional components do not use this, avoiding a lot of common bugs and complexity.this 关键字,通常需要在构造函数中绑定事件处理程序。函数组件不使用 this,从而避免了许多常见的 Bug 和复杂性。There are 3 ways to style a react application with CSS:
English Answer: Props (Properties) are used to pass data from a parent component to a child component. They are read-only and immutable within the child component, following a unidirectional data flow (parent to child).
中文翻译: Props(属性)用于将数据从父组件传递给子组件。它们在子组件中是只读且不可变的,遵循单向数据流原则(即数据只能由父传子)。
Example:
x1function 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;State is a built-in React object used to manage data locally within a component. Unlike props, state is mutable.
State(状态)是 React 内置的对象,用于在组件内部管理局部数据。与 Props 不同,State 是可变的。
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.
English Answer: In functional components, we use the useState hook. It provides a state variable and a setter function.
代码示例 (Example):
xxxxxxxxxx71const [count, setCount] = useState(0);23// Direct Update4setCount(10);56// Functional Update (Safe way to increment)7setCount(prevCount => prevCount + 1);中文翻译: 在函数组件中,我们使用 useState Hook。它提供一个状态变量和一个 setter 函数。
需要注意的是:
English Answer:
state.value = 10. React won't know the state changed, and the UI won't re-render.中文翻译:
state.value = 10。React 无法感知这种变化,UI 也不会重新渲染。
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:
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;这是最直观、最常用的方式。你在 onClick 中定义一个匿名的箭头函数,然后在函数体内部调用目标方法并传入参数。
xxxxxxxxxx11<button onClick={() => handleClick(id)}>Delete</button>这是一种较为传统的方式,它会创建一个绑定了特定 this 和参数的新函数。
bind method to pre-configure the function with specific arguments. The first argument of bind is the context (this).bind 方法预先配置带有特定参数的函数。bind 的第一个参数是上下文(this)。xxxxxxxxxx11<button onClick={handleClick.bind(this, id)}>Delete</button>如果你在渲染超长列表,为了避免在每个循环中都创建新的匿名函数(这会产生轻微的内存开销),可以利用 HTML 的 data-* 属性。
data-* attributes and retrieve them from the event object (e.target.dataset).data-* 属性中,然后从事件对象中获取(通过 e.target.dataset).xxxxxxxxxx61const handleClick = (e) => {2 const id = e.target.dataset.id;3 console.log(id);4};56<button data-id={id} onClick={handleClick}>Delete</button>💡 关键对比与面试要点
| 方式 | 优点 | 缺点 |
|---|---|---|
| 箭头函数 | 语法简洁,可读性最高。 | 每次渲染都会创建一个新函数。 |
| bind | 官方早期推荐。 | 语法略显臃肿,在函数组件中较少使用。 |
| Data Attributes | 性能最好,函数引用保持不变。 | 只能传递字符串类型,代码不够直观。 |
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.
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.
English Answer: Refs (References) are used to access and interact with DOM nodes or React elements directly. While React usually encourages data flow via props, Refs are necessary for "imperative" actions such as:
useRef hook.中文翻译: Refs(引用)用于直接访问和操作 DOM 节点或 React 元素。虽然 React 通常鼓励通过 Props 进行数据流转,但在某些“命令式”场景下 Refs 是必需的,例如:
useRef Hook 来实现。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;English Answer (Optimized): Custom Hooks are JavaScript functions whose names start with "use". They allow you to extract component logic into reusable functions. Custom Hooks can call other Hooks (like useState or useEffect). They solve the problem of logic duplication across components without adding unnecessary nesting to the component tree.
中文翻译: 自定义 Hooks 是名称以 "use" 开头的 JavaScript 函数。它们允许你将组件逻辑提取到可复用的函数中。自定义 Hooks 内部可以调用其他 Hooks(如 useState 或 useEffect)。它们解决了组件间逻辑重复的问题,且不会给组件树增加不必要的嵌套。
English Answer (Optimized): Context provides a way to share data (like themes, user info, or language settings) globally across a tree of components without having to pass props down manually through every level (a problem known as Prop Drilling). It consists of a Provider to wrap the parent tree and a useContext hook (or Consumer) to access the data in child components.
中文翻译: Context 提供了一种在组件树中全局共享数据(如主题、用户信息或语言设置)的方法,而无需手动通过每一层传递 Props(即解决 Props 钻取问题)。它由用于包裹父树的 Provider 和用于在子组件中访问数据的 useContext Hook(或 Consumer)组成。
English Answer (Optimized): React Router is the standard library for routing in React applications. It enables navigation between different views (components) without refreshing the entire page, creating a seamless Single Page Application (SPA) experience. In modern versions (v6+), it uses a declarative approach with components like <Routes>, <Route>, and hooks like useNavigate.
中文翻译: React Router 是 React 应用中处理路由的标准库。它实现了在不同视图(组件)之间进行导航而无需刷新整个页面,从而创造无缝的单页面应用 (SPA) 体验。在现代版本 (v6+) 中,它通过 <Routes>、<Route> 等组件以及 useNavigate 等 Hook 采用声明式的方式进行路由管理。