是从https://www.geeksforgeeks.org/reactjs/react-interview-questions/获取的。
💡 核心回答:React 是如何工作的?
React 的核心工作原理可以概括为:“声明式 UI” + “虚拟 DOM” + “组件化”。
第一步:声明式 UI (Declarative UI)
你只需要告诉 React “页面现在应该长什么样”(通过 State 状态),而不需要手动去操作浏览器 DOM(比如 appendChild 或 removeChild)。
通俗点说:你只负责换“剧本”(状态),React 负责“演戏”(更新界面)。
第二步:虚拟 DOM 与 Diff 算法 (Virtual DOM & Diffing)
第三步:组件化 (Component-Based)
React 把界面拆分成一个个独立的、可复用的组件。每个组件有自己的逻辑和状态,最后像搭积木一样拼成复杂的应用。
答案:
1. 核心回答 (Core Answer) 可以只背诵这一个,下面两个先了解
English: React works based on a Declarative approach and a Component-based architecture. The core mechanism involves the Virtual DOM, the Diffing algorithm, and the Fiber Reconciler.
- Declarative UI: We describe "what" the UI should look like based on the current state, and React handles "how" to update the DOM.
- Virtual DOM & Diffing: When state changes, React creates a new Virtual DOM tree and compares it with the previous one (this is called Diffing) to find the minimum set of changes.
- Fiber & Concurrent Rendering: In modern React, the Fiber engine allows React to break rendering work into small units and prioritize urgent tasks like user inputs, ensuring a smooth user experience.
中文翻译: React 基于声明式设计和组件化架构工作。其核心机制包括虚拟 DOM、Diff 算法和 Fiber 协调器。
- 声明式 UI: 我们只需根据当前状态描述 UI “应该长什么样”,React 会处理“如何”更新 DOM 的细节。
- 虚拟 DOM 与 Diff: 当状态改变时,React 会创建一棵新的虚拟 DOM 树,并将其与上一棵进行对比(即 Diff 过程),从而找出最小的差异。
- Fiber 与并发渲染: 在现代 React 中,Fiber 引擎允许 React 将渲染工作拆分为小单元,并优先处理用户输入等紧急任务,确保用户体验流畅。
2. 渲染流程三部曲 (Three-Step Process)
English:
- Trigger: A state change or a prop update triggers a re-render.
- Render Phase: React executes the component functions and generates the Fiber tree. This phase is asynchronous and can be paused or interrupted (Concurrent feature).
- Commit Phase: React applies the calculated changes to the real DOM in a single synchronous step to ensure UI consistency.
中文翻译:
- 触发: 状态改变或 Props 更新触发重新渲染。
- 渲染阶段 (Render Phase): React 执行组件函数并生成 Fiber 树。这个阶段是异步的,可以被暂停或中断(这是并发特性)。
- 提交阶段 (Commit Phase): React 将计算出的变更一次性同步应用到真实 DOM 上,以确保 UI 的一致性。
3. 针对 Next.js 的进阶补充 (Advanced Bonus for Next.js)
English: In the latest Next.js (App Router), React also supports Server Components. Some components are pre-rendered on the server to reduce the client-side JavaScript bundle, while Hydration connects the client-side interactivity to the server-rendered HTML.
中文翻译: 在最新的 Next.js (App Router) 中,React 还支持服务端组件 (RSC)。部分组件直接在服务端预渲染以减少客户端的 JS 包体积,而水合 (Hydration) 过程则负责将客户端交互绑定到服务端生成的 HTML 上。
English Answer (Optimized): JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like structures within your JS code. It makes UI code more readable and expressive.
React.createElement() calls by Babel. In modern React (v17+), it uses the new JSX transform, which automatically imports special functions from the React package (like jsx()) without needing import React from 'react' in every file.中文翻译: JSX (JavaScript XML) 是 JavaScript 的语法扩展,允许你在 JS 代码中编写类似 HTML 的结构。它使 UI 代码更具可读性和表现力。
React.createElement() 调用。在现代 React (v17+) 中,使用了新的 JSX 转换机制,它会自动从 React 包中导入特定函数(如 jsx()),因此不再需要在每个文件中手动 import React。已经有答案了。
已经有答案了。
English Answer (Optimized): Props (short for properties) are read-only inputs passed from a parent component to a child component to customize its behavior or display.
static defaultProps, in Functional Components, the standard way to define default values is by using ES6 destructuring assignment directly in the function parameters (e.g., const MyComp = ({ name = "Guest" }) => ...).中文翻译: Props(属性的缩写)是从父组件传递给子组件的只读输入,用于自定义组件的行为或显示。
static defaultProps,但在函数组件中,标准做法是直接在函数参数中使用 ES6 解构赋值来定义默认值(例如:const MyComp = ({ name = "访客" }) => ...)。已经有答案了。
已经有答案了。
English Answer: Fragments allow you to group multiple elements without adding extra nodes to the DOM.
<div>), which can clutter the DOM and break layouts (e.g., in tables or flexboxes).<React.Fragment> (to provide a key) or the short syntax <>...</>.中文翻译: Fragment(片段)允许你将多个元素组合在一起,而无需向 DOM 中添加额外的节点。
<div>),这可能会导致 DOM 结构臃肿并破坏布局(例如在表格或弹性布局中)。<React.Fragment>(以便提供 key)或简写语法 <>...</>。English Answer (Optimized):
onChange, making the state the "single source of truth." This is ideal for real-time validation.useRef) only when needed (e.g., on form submission). This is useful for simple forms or integrating with non-React libraries.中文翻译:
onChange 更新状态,使状态成为“单一数据源”。这非常适合实时校验。useRef) 访问数值。这适用于简单表单或集成非 React 库的场景。React does not manage the form input’s state. Instead, the DOM itself keeps track of the input’s value. You can access the value when needed using refs
React.createRef() or useRef() to access the current value.English Answer (Optimized): Hooks are special built-in functions that allow functional components to use state, lifecycle methods, and other React features. They were introduced to solve several issues:
componentDidMount and componentWillUnmount). Hooks allow related logic to be grouped together.this keyword and class-related boilerplate.中文翻译: Hooks 是特殊的内置函数,允许函数组件使用状态、生命周期方法和其他 React 特性。 引入 Hooks 是为了解决以下问题:
useState hook work?The useState hook allows you to add state to functional components. It returns a state variable and a setter function to update that state. When the state changes, React re-renders the component with the updated value.
Example:
xxxxxxxxxx121import { useState } from 'react';23function Counter() {4 const [count, setCount] = useState(0);56 return (7 <div>8 <p>Count: {count}</p>9 <button onClick={() => setCount(count + 1)}>Increment</button>10 </div>11 );12}In this example:
count is the current state value.setCount is the function used to update state.0 is the initial value when the component mounts. When setCount is called, React re-renders Counter with the new count value.English Answer (Optimized): useEffect handles "side effects" like data fetching, subscriptions, or manual DOM updates. The dependency array controls when the effect re-runs:
[]: Runs only once after the initial mount (similar to componentDidMount).[a, b]: Runs after the initial mount and whenever any value in the array changes.中文翻译: useEffect 用于处理“副作用”,如数据获取、订阅或手动操作 DOM。 依赖项数组决定了 Effect 何时重新执行:
[]:仅在组件挂载后执行一次(类似于 componentDidMount)。[a, b]:在组件挂载后执行,以及数组中任何值发生变化时执行。Example :
xxxxxxxxxx41useEffect(() => {2 console.log('Effect runs');3 return () => console.log('Cleanup runs');4}, [dependency]);useEffect and useLayoutEffect?English Answer (Optimized):
useEffect (Standard): Runs asynchronously after the browser has painted the screen. It is non-blocking and suitable for most tasks like data fetching.useLayoutEffect (Specific): Runs synchronously after DOM mutations but before the browser paints. It is blocking and used for measuring DOM elements or preventing "flickering" when updating styles based on layout.中文翻译:
useEffect(标准):在浏览器绘制屏幕之后异步执行。它是非阻塞的,适用于大多数任务,如获取数据。useLayoutEffect(特定):在 DOM 变更后、浏览器绘制之前同步执行。 它是阻塞的,用于测量 DOM 元素或在基于布局更新样式时防止页面“闪烁”。useContext hook and when should you use it?The useContext hook allows functional components to consume values from a React Context without passing props through every level of the component tree (avoiding “prop drilling”).
When to use it:
useReducer hook and when is it preferred over useState?English Answer (Optimized): useReducer is a hook for managing complex state logic, working similarly to Redux. It takes a reducer function and an initialState, returning the current state and a dispatch function. Use it when:
中文翻译: useReducer 是用于管理复杂状态逻辑的 Hook,工作原理类似于 Redux。 它接收一个 reducer 函数和 initialState(初始状态),返回当前状态和 dispatch 函数。 适用场景:
useRef hook and what are its common use cases?The useRef hook creates a mutable object that persists across renders without causing re-renders. It is commonly used to access DOM elements or store mutable values.
Example:
xxxxxxxxxx161import { useRef } from 'react';23function App() {4 const inputRef = useRef();56 const focusInput = () => {7 inputRef.current.focus();8 };910 return (11 <div>12 <input ref={inputRef} type="text" />13 <button onClick={focusInput}>Focus</button>14 </div>15 );16}In this example:
inputRef stores a reference to the input DOM node.inputRef.current.focus() focuses the input without re-rendering the component.Common use cases:
useMemo and useCallback?English Answer (Optimized): Both are used for performance optimization through memoization:
useMemo: Caches the result of a calculation. Use it to avoid expensive re-computations on every render.useCallback: Caches the function instance itself. Use it to prevent child components from re-rendering unnecessarily when you pass functions as props.中文翻译: 两者都通过记忆化(Memoization)用于性能优化:
useMemo:缓存计算的结果。用于避免每次渲染时进行昂贵的重复计算。useCallback:缓存函数实例本身。当你将函数作为 Props 传递时,用于防止子组件进行不必要的重新渲染。Custom hooks are reusable functions that let you extract and share logic between functional components. They are JavaScript functions whose names start with use and can call other hooks like useState or useEffect.
Example:
xxxxxxxxxx251import { useState, useEffect } from 'react';23function useFetch(url) {4 const [data, setData] = useState(null);5 const [loading, setLoading] = useState(true);67 useEffect(() => {8 fetch(url)9 .then(res => res.json())10 .then(data => {11 setData(data);12 setLoading(false);13 });14 }, [url]);1516 return { data, loading };17}1819// Usage in a component20function App() {21 const { data, loading } = useFetch('https://api.example.com/data');2223 if (loading) return <p>Loading...</p>;24 return <div>{JSON.stringify(data)}</div>;25}In this example, useFetch is a custom hook that fetches data from an API and manages loading state. The hook is reused in App to keep the component clean and separate the data-fetching logic.
English Answer:
中文翻译:
English Answer (Optimized):
useState or useReducer. It is used for UI-specific logic like form inputs, toggles, or modal visibility.中文翻译:
useState 或 useReducer 在单个组件内部管理的数据。用于处理 UI 逻辑,如表单输入、开关切换或模态框显示。There are several approaches and libraries for managing state in React and Next.js, depending on the scale and complexity of your application:
useState, useReducer, useContext – for local or small-scale state management.English Answer (Optimized): While both solve "Prop Drilling," they serve different purposes:
中文翻译: 虽然两者都能解决“Props 钻取”问题,但用途不同:
English Answer:
中文翻译:
The Context API in React is used to share data globally across components without prop drilling. It allows you to wrap components with a provider and access the shared value anywhere in the tree using useContext.createContext() : Creates a context.
Consumer.The useReducer hook in React plays an important role in state management when the logic for updating state is complex or involves multiple actions. Unlike useState, which is best for simple state updates, useReducer organizes state transitions using a reducer function, making the code more predictable and easier to maintain. It is especially useful in larger applications or when managing related pieces of state.
useState.dispatch triggers actions.English Answer (Optimized): To ensure data survives a page reload, we use:
localStorage (persists until cleared) or sessionStorage (persists until tab is closed). Usually synced with state inside a useEffect.redux-persist or Zustand's persist middleware) to automatically sync the store with localStorage.中文翻译: 为了确保数据在页面刷新后不丢失,我们使用:
localStorage(持久存储直至清除)或 sessionStorage(关闭标签页后清除)。 通常在 useEffect 中与状态同步。redux-persist 或 Zustand 的 persist 插件)来自动将 store 与 localStorage 同步。In React, sometimes you need values that depend on other state or props. These values can be handled as derived state or computed state, but they work differently:
useMemo. Ensures data stays consistent without storing redundant state.Optimizing state updates ensures that components re-render only when necessary, improving performance in React applications:
English Answer (Optimized): Since React state updates are asynchronous and batched for performance:
setCount(prev => prev + 1).AbortController inside useEffect to ensure only the latest request's result is saved to the state.loading and error when dealing with async API calls.中文翻译: 由于 React 的状态更新是异步的且为了性能会进行批处理:
setCount(prev => prev + 1)。useEffect 中使用清理变量或 AbortController,确保只有最后一次请求的结果被保存到状态中。loading 和 error 状态。
English Answer (Optimized):
中文翻译:
English Answer (Optimized): React’s Diffing algorithm is based on two main assumptions to keep the complexity at O(n):
<div> to a <span>), React will tear down the old tree and build a new one.key prop to identify which items have changed, been added, or been removed. This allows React to reorder elements instead of re-rendering the entire list.中文翻译: React 的 Diff 算法基于两个主要假设,从而将复杂度控制在 O(n):
<div> 变成 <span>),React 会销毁旧树并构建全量新树。key 属性来识别哪些项发生了变化、被添加或被移除。这允许 React 仅进行移动操作,而不是重新渲染整个列表。English Answer (Optimized): Reconciliation is the process through which React updates the DOM. It involves:
中文翻译: 协调(Reconciliation)是 React 更新 DOM 的过程。它包括:
React.memo help improve performance?English Answer: React.memo is a Higher-Order Component used for performance optimization. It performs a shallow comparison of a component's props. If the props haven't changed between renders, React skips rendering that component and reuses the last rendered result. It is most effective for components that render often with the same props.
中文翻译: React.memo 是一个用于性能优化的高阶组件。它对组件的 Props 进行浅比较。如果两次渲染之间 Props 没有变化,React 就会跳过该组件的渲染并复用上次的结果。它对于那些经常带着相同 Props 频繁渲染的组件最为有效。
To improve performance in a slow React application, you can use several optimization techniques:
Code splitting and lazy loading are techniques used to improve performance by reducing the initial load time of a React application.
In React, this is often implemented with React.lazy and <Suspense>:
xxxxxxxxxx91const MyComponent = React.lazy(() => import('./MyComponent'));23function App() {4 return (5 <Suspense fallback={<div>Loading...</div>}>6 <MyComponent />7 </Suspense>8 );9}English Answer (Optimized):
React.memo for components, and useCallback/useMemo for stabilizing references and values.React.lazy and Suspense to load components only when needed, reducing initial bundle size.key props. For very long lists, use "Windowing" or "Virtualization" (e.g., react-window).中文翻译:
React.memo 包裹组件,使用 useCallback 和 useMemo 来稳定引用和计算值。React.lazy 和 Suspense 按需加载组件,减少初始包体积。key。对于超长列表,使用“窗口化”或“虚拟滚动”(如 react-window)。Both Component and PureComponent are used to create class components, but they handle re-rendering differently:
setState is called, regardless of whether the state or props have changed.Components automatically re-render when their state or props change, but React optimizes this process using the virtual DOM:
Form inputs can be controlled or uncontrolled, and this affects how they are rendered and updated:
onChange.In React, re-renders can be expensive if functions or computed values are recreated unnecessarily. useMemo and useCallback help optimize rendering by caching values and functions:
In React, lists are usually rendered using JavaScript’s .map() method. Each list item should also have a unique key prop so React can efficiently track and update elements.
xxxxxxxxxx81const fruits = ["Apple", "Banana", "Mango"];2return (3 <ul>4 {fruits.map((fruit, index) => (5 <li key={index}>{fruit}</li>6 ))}7 </ul>8);In this Example, .map() is used to iterate over the array, and the key prop helps React identify each list item uniquely.
在 React 中,我们使用 JavaScript 的 .map() 方法来遍历数组并返回一个 JSX 元素数组。
.map()? 因为它会返回一个新数组,React 可以直接在 JSX 中将其渲染出来。key prop important in React lists?The key prop is important because it helps React efficiently manage list rendering. It allows React to identify which items have changed, been added, or removed, instead of re-rendering the entire list.
中文翻译: Key 是列表中每个元素的唯一标识符。它们帮助 React 的协调 (Reconciliation) 过程:
Using the array index as a key technically works, but it is not recommended in most cases. If the list changes (items are reordered, added, or removed), React may reuse components incorrectly, leading to UI bugs.
It is safe only for static lists that never change.
中文翻译: 使用索引作为 Key 是最后的手段。如果列表会发生变化(排序、过滤、增删),则应避免使用索引。
In React, list items can be conditionally rendered using techniques like if statements, ternary operators, or array methods such as .filter() combined with .map().
Example:
xxxxxxxxxx81const users = [{name: "Aman", active: true}, {name: "Raj", active: false}];2return (3 <ul>4 {users5 .filter(user => user.active)6 .map(user => <li key={user.name}>{user.name}</li>)}7 </ul>8);State is immutable, so you cannot modify arrays directly. Instead, you create a new array using methods like .map() or .filter() and then update state with that new array.
Example (removing an item):
xxxxxxxxxx51const [list, setList] = useState(["A", "B", "C"]);23const removeItem = (item) => {4 setList(list.filter(i => i !== item));5};In this example, .filter() creates a new array without the removed item, and setList updates the state.
Rendering very large lists can hurt performance, so React provides techniques and best practices to optimize them:
react-window or react-virtualized to render only the visible portion of the list.React.memo to prevent unnecessary re-renders.You can nest .map() calls: one for the parent array and another for the child array.
Example:
xxxxxxxxxx191const categories = [2 { name: "Fruits", items: ["Apple", "Banana"] },3 { name: "Veggies", items: ["Carrot", "Tomato"] }4];56return (7 <div>8 {categories.map(cat => (9 <div key={cat.name}>10 <h3>{cat.name}</h3>11 <ul>12 {cat.items.map(item => (13 <li key={item}>{item}</li>14 ))}15 </ul>16 </div>17 ))}18 </div>19);In this example, each level of data gets its own .map() loop, and both parent and child elements should have unique key props.
In React, since state is immutable, you cannot directly modify the existing array. Instead, you create a new array that includes the new item and update state.
Example:
xxxxxxxxxx51const [list, setList] = useState(["A", "B"]);23const addItem = (item) => {4 setList([list, item]);5};In this example:
[...list, item] creates a new array with the existing items plus the new one.setList with this new array updates the state and triggers a re-render, showing the updated list in the UI.In React, lists are usually stored in state, and you can sort or filter them dynamically by creating a new array based on the original list and updating the state.
Example:
xxxxxxxxxx111const [users, setUsers] = useState([2 { name: "Aman", age: 25 },3 { name: "Raj", age: 30 },4 { name: "Sara", age: 22 }5]);67// Filter active users8const filteredUsers = users.filter(user => user.age > 24);910// Sort by name11const sortedUsers = [users].sort((a, b) => a.name.localeCompare(b.name));In this example:
filter creates a new array containing only the items that meet the condition.sort rearranges the array items; using [...users] ensures the original state is not mutated.When rendering lists, it’s important to return JSX elements for each item. The choice between map() and forEach() affects this:
Example using map():
xxxxxxxxxx61const fruits = ["Apple", "Banana", "Mango"];2return (3 <ul>4 {fruits.map(fruit => <li key={fruit}>{fruit}</li>)}5 </ul>6);In this example:
map returns an array of <li> elements, which React renders.forEach here would not work, because it does not return the array of elements.
In plain HTML, the browser’s DOM manages form data. In React, form inputs are usually controlled components:
xxxxxxxxxx191function MyForm() {2 const [name, setName] = React.useState("");34 const handleSubmit = (e) => {5 e.preventDefault();6 alert("Submitted: " + name);7 };89 return (10 <form onSubmit={handleSubmit}>11 <input 12 type="text" 13 value={name} 14 onChange={(e) => setName(e.target.value)} 15 />16 <button type="submit">Submit</button>17 </form>18 );19}In this example, the input is fully controlled by React through value and onChange.
By using event.preventDefault() inside the form’s onSubmit handler.
Example:
xxxxxxxxxx41const handleSubmit = (e) => {2 e.preventDefault();3 console.log("Form submitted!");4};In this example, the page is stopped from reloading and lets React control what happens on submit.
event.stopPropagation().xxxxxxxxxx41const handleClick = (e) => {2 e.stopPropagation();3 console.log("Child clicked, but won’t bubble up.");4};By using a single state object and updating it dynamically with name and value.
Example:
xxxxxxxxxx51const [formData, setFormData] = useState({ name: "", email: "" });23const handleChange = (e) => {4 setFormData({ formData, [e.target.name]: e.target.value });5};This way, one handler can manage multiple inputs.
In React, form inputs are usually controlled components, meaning their values are stored in state. To reset a form, you simply reset the state that controls the inputs:
Example:
xxxxxxxxxx81const [formData, setFormData] = useState({ name: "", email: "" });23const handleSubmit = (e) => {4 e.preventDefault();5 console.log(formData);6 // Reset form fields7 setFormData({ name: "", email: "" });8};In this example:
setFormData({ name: "", email: "" }) resets all input fields to their initial values.
React Router is a library that enables client-side routing in React applications. It allows you to create single-page applications (SPAs) where navigation between views happens without a full page reload, making apps faster and smoother.
React Router 是 React 客户端路由的标准库。它允许你创建单页面应用 (SPA),在切换导航时无需重新加载整个页面。通过拦截 URL 的变化并按需渲染组件,它让用户体验变得更快速、更流畅。
<a> tag and <Link> in React Router?<a> tag: Reloads the whole page when navigating.<Link> component: Updates the URL and changes the component without reloading (SPA behavior).中文翻译:
<a> 标签:执行传统的浏览器导航,会触发全页刷新。这会导致应用状态丢失,且速度较慢。<Link> 组件:拦截点击事件并使用 HTML5 History API 更新 URL。它在不刷新页面的情况下切换视图,从而保留应用的状态。<BrowserRouter> – Wraps the app and enables routing.<Routes> – Container for all route definitions.<Route> – Defines a path and the component to render.<Link> / <NavLink> – For navigation.useNavigate() – For programmatic navigation.中文翻译:
<BrowserRouter>:父级包裹组件,利用浏览器的 history API 启用路由功能。<Routes>:所有具体路由定义的容器,取代了旧版的 <Switch>。<Route>:定义特定路径 (path) 与要渲染的组件 (element) 之间的映射关系。<Link> / <NavLink>:用于导航;<NavLink> 会为当前激活的链接添加 "active" 类名。useNavigate():用于编程式导航的 Hook(例如在表单提交后进行跳转)。useHistory and useNavigate?useHistory (v5): Used an object-oriented approach to manage navigation (e.g., history.push('/path')).
useNavigate (v6): Replaced useHistory. It provides a simpler, functional API. Instead of push or replace, you call the function directly: Maps('/path') or Maps('/path', { replace: true }).
xxxxxxxxxx21const navigate = useNavigate(); 2navigate("/dashboard"); 中文翻译:
useHistory (v5版本):使用面向对象的方式管理导航(例如 history.push('/path'))。useNavigate (v6版本):取代了 useHistory。它提供了一个更简单的函数式 API。不再使用 push 或 replace 方法,而是直接调用函数:Maps('/path') 或 Maps('/path', { replace: true })。English Answer (Optimized): In v6, you nest <Route> components inside each other. The parent component must use the <Outlet /> component to specify where the child components should be rendered.
xxxxxxxxxx71<Routes>2 <Route path="/dashboard" element={<Dashboard />}>3 <Route path="profile" element={<Profile />} />4 </Route>5</Routes>6// Inside Dashboard.js:7return (<div> <Sidebar /> <Outlet /> </div>);中文翻译: 在 v6 中,你将 <Route> 组件互相嵌套。父组件必须使用 <Outlet /> 组件来指定子组件应该在何处渲染。 (示例:访问 /dashboard/profile 时,Profile 组件会出现在 Dashboard 的 Outlet 位置。)
English Answer: Route parameters are dynamic segments of a URL, defined using a colon (e.g., :id). You access them using the useParams hook.
/users/:id, if the URL is /users/101, useParams() returns { id: '101' }.中文翻译: 路由参数是 URL 中的动态部分,使用冒号定义(如 :id)。你可以使用 useParams Hook 来访问它们。
/users/:id,当访问 /users/101 时,useParams() 返回 { id: '101' }。xxxxxxxxxx11<Route path="/users/:id" element={<User />} />Inside User component:
xxxxxxxxxx21import { useParams } from "react-router-dom";2const { id } = useParams();/users/101 : id = 101
English Answer:
<Navigate /> component inside a <Route> element.useNavigate() hook inside a function (e.g., Maps('/login')).中文翻译:
<Route> 的 element 中使用 <Navigate /> 组件。useNavigate() Hook(例如 Maps('/login'))。<Navigate> component:xxxxxxxxxx11<Route path="/old" element={<Navigate to="/new" />} />Using useNavigate() hook for programmatic redirects.
client-side routing and server-side routing?English Answer:
中文翻译:
<Switch> and <Routes> in React RouterEnglish Answer (Optimized):
<Switch> (v5): Matches routes based on order (first match wins). It often required the exact prop to avoid incorrect matches.<Routes> (v6): Uses a smart ranking algorithm to pick the "best" match regardless of order. It is more predictable, eliminates the need for the exact prop, and simplifies nested route logic.中文翻译:
<Switch> (v5版本):基于顺序匹配路由(匹配到第一个就停止)。通常需要 exact 属性来避免错误的匹配。<Routes> (v6版本):使用智能权重算法来选择“最佳”匹配,而不管定义的顺序如何。它更具预测性,不再需要 exact 属性,并简化了嵌套路由逻辑。
This set contains the advanced-level questions asked in the interview.
English Answer (Optimized): Custom Hooks are JavaScript functions whose names start with "use". They allow you to extract and reuse stateful logic across multiple components, adhering to the DRY (Don't Repeat Yourself) principle.
useFetch (API calls), useLocalStorage (persistence), useDebounce (search optimization).中文翻译: 自定义 Hooks 是以 "use" 开头的 JavaScript 函数。它们允许你在多个组件之间提取并复用有状态的逻辑,遵循 DRY (不写重复代码) 原则。
useFetch(API 请求)、useLocalStorage(数据持久化)、useDebounce(搜索防抖)。English Answer (Optimized):
React.memo, useMemo, and useCallback to prevent unnecessary re-renders.React.lazy and Suspense for lazy loading components.React.Fragment or <>...</> to avoid adding extra nodes to the DOM.keys for list rendering.中文翻译:
React.memo、useMemo 和 useCallback 来防止不必要的重复渲染。React.lazy 和 Suspense 对组件进行懒加载。React.Fragment 或 <>...</> 避免向 DOM 中添加多余节点。key。English Answer:
useRef: A hook used in functional components. It persists the same ref object across re-renders.createRef: A function used in class components. It creates a new ref object every time the component renders. If used in a functional component, it would lose its value on every re-render.中文翻译:
useRef:在函数组件中使用的 Hook。它在组件多次重新渲染之间保持同一个 ref 对象。createRef:在类组件中使用的函数。每次组件渲染时它都会创建一个新的 ref 对象。如果在函数组件中使用它,每次重渲染都会导致值丢失。English Answer (Optimized): React Redux is the official UI binding library for Redux. It allows React components to read data from a Redux store and dispatch actions to update the state. Benefits:
中文翻译: React Redux 是 Redux 的官方 React 绑定库。它允许 React 组件从 Redux store 中读取数据,并派遣 (dispatch) action 来更新状态。 优点:
English Answer:
type and payload).combineReducers: A helper function to turn an object whose values are different reducing functions into a single combined reducer you can pass to createStore.中文翻译:
type 和 payload)。combineReducers:一个辅助函数,用于将多个 reducer 函数合并成一个根 reducer,以便传递给 createStore。English Answer (Optimized): The Context API is a built-in feature to share data across nested components without "prop drilling."
useContext: Components that subscribe to context changes. In modern functional components, useContext(MyContext) is the preferred way to consume data instead of the <Consumer> wrapper.中文翻译: Context API 是 React 内置的功能,用于在嵌套组件间共享数据,避免“Props 钻取”。
useContext:订阅 Context 变化的组件。在现代函数组件中,useContext(MyContext) 是首选的消费数据方式,取代了旧的 <Consumer> 包裹组件。In ReactJS, Cross-Origin Resource Sharing (CORS) refers to the method that allows you to make requests to the server deployed at a different domain. As a reference, if the frontend and backend are at two different domains, we need CORS there.
We can setup CORS evironment in frontend using two methods:
Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST endpoints. This library is very useful to perform CRUD operations.
To install aixos package in react use the following command.
xxxxxxxxxx11npm i axiosxxxxxxxxxx301import React, { useState } from "react";23const App = () => {4 const [counter, setCounter] = useState(0)5 const handleClick1 = () => {6 setCounter(counter + 1)7 }89 const handleClick2 = () => {10 setCounter(counter - 1)11 }1213 return (14 <div>15 <div>16 {counter}17 </div>18 <div className="buttons">19 <button onClick={handleClick1}>20 Increment21 </button>22 <button onClick={handleClick2}>23 Decrement24 </button>25 </div>26 </div>27 )28}2930export default AppOutput:

In this example
English Answer (Optimized): State updates in React are asynchronous and may be batched. If you update state based on the previous value (e.g., setCount(count + 1)), it might use a stale value from a previous render. Using a callback (setCount(prev => prev + 1)) ensures you are always working with the latest state, preventing race conditions and bugs.
中文翻译: React 的状态更新是异步的,并且可能会进行批处理。如果你基于旧值更新状态(如 setCount(count + 1)),它可能会使用旧渲染周期中的过时值。 使用回调函数(如 setCount(prev => prev + 1))能确保你始终在最新的状态基础上进行操作,从而防止竞态条件和 Bug。
不需要管。
过时了。
The useMemo is a hook used in the functional component of react that returns a memoized value. In Computer Science, memoization is a concept used in general when we don’t need to recompute the function with a given argument for the next time as it returns the cached result. A memoized function remembers the results of output for a given set of inputs.
React do not update immediately, although it seems immediate at first glance. React keep track of the states by queuing them in the order they are called. React queue all the changes to be made and update once the component Re-render which is not immediate. This is how React knows which value corresponds to which state. It goes as per the queue every time the component tries to re-render.
中文翻译:
useEffect:用于处理副作用(获取数据、手动操作 DOM、订阅)。在渲染之后执行。useMemo:缓存计算后的值。用于昂贵的计算,避免每次渲染时都重复计算。useCallback:缓存函数实例。当向经过 memo 优化的子组件传递函数时使用,以防止子组件不必要的重渲染。 注:useState 的更新不是立即生效的;它会触发一次重渲染,新值在下一次渲染中才可用。There are three types of routers in React:
The React StrictMode can be viewed as a helper component that allows developers to code efficiently and brings to their attention any suspicious code which might have been accidentally added to the application. The StrictMode can be applied to any section of the application, not necessarily to the entire application.
xxxxxxxxxx111import React from "react";2import ReactDOM from "react-dom/client";3import App from "./App";45const root = ReactDOM.createRoot(document.getElementById("root"));67root.render(8 <React.StrictMode>9 <App />10 </React.StrictMode>11);Conditional rendering in React means dynamically displaying components or elements based on a condition. Instead of rendering everything at once, React decides what to render based on the current state, props, or logic. We can use conditional rendering when:
已经有答案了。
已经有答案了。
In React, data is passed between components using props. The way data flows between components depends on whether they are parent-child, sibling components, or if you're using state management techniques like context or Redux.
English Answer: Lazy Loading is a performance optimization technique that loads components only when they are needed. In React, this is achieved using React.lazy() and <Suspense>. It helps reduce the initial bundle size, leading to faster initial page loads.
中文翻译: 懒加载 (Lazy Loading) 是一种性能优化技术,仅在需要时才加载组件。在 React 中,通过 React.lazy() 和 <Suspense> 来实现。它有助于减少初始包体积,从而加快页面的首次加载速度。
Redux is a state management library that helps manage the application state globally. React-Redux is used to connect Redux state to React components. There are the three main components of the redux:
React Routing is used in Single Page Applications (SPAs), while conventional routing typically applies to multi-page applications. Here’s how they differ:
| Features | React Routing | Conventional Routing |
|---|---|---|
| Page Loading | No full page reload; components are dynamically rendered. | Entire page reload happens with every navigation. |
| SEO Considerations | React Router needs additional configurations (like SSR or dynamic rendering) to optimize SEO. | SEO is typically easier to manage since pages are fully rendered by the server. |
| Navigation | Navigation is handled by JavaScript on the client-side, often using Link and NavLink components. | Navigation is handled by the server through HTML anchor tags (). |
| Technology | Managed via React Router; uses client-side routing. | Managed by server-side routing (e.g., Express, PHP). |
| URL Structure | URLs can have dynamic parameters handled by React Router (e.g., /product/:id). | URLs are typically static and are managed by the server. |
English Answer: The main difference lies in how the browser handles transitions:
中文翻译: 主要区别在于浏览器如何处理页面切换:
In React, props (short for "properties") are a way of passing data from a parent component to a child component. Props are read-only and are used to customize or control the behavior of a component. They help make components reusable and dynamic by allowing different data to be passed into them.
CSS Modules help you keep your styles specific to each React component, so they don't affect other components. In simple terms, it lets you write CSS for one component without worrying about messing up the styles of other parts of your app. This is especially useful when your app grows larger and has many components, making it easier to manage styles without conflicts.