引言
在现代前端开发面试中,React作为最流行的前端框架之一,其手写代码题往往是考察候选人基础功底和实际问题解决能力的关键环节。手写代码不仅测试你对React核心概念的理解,还考察你的代码组织能力、性能优化意识以及对最佳实践的掌握程度。本文将系统性地梳理React面试中的手写代码题型,从基础到高阶,提供详细的解析和代码实现技巧,帮助你全面备战React面试。
一、基础概念与核心API手写题
1.1 手写useState和useEffect
题目
:请手写一个简化的useState和useEffect实现,理解React Hooks的工作原理。
解析
:这是考察对React Hooks底层原理理解的经典题目。面试官希望看到你对闭包、状态管理和副作用处理的理解。
代码实现
:
// 模拟React的全局状态管理
let currentComponent = null;
let hookIndex = 0;
function useState(initialState) {
// 获取当前组件的hook状态
const component = currentComponent;
const index = hookIndex;
// 初始化状态
if (!component.hooks[index]) {
component.hooks[index] = {
state: initialState,
deps: null
};
}
const hook = component.hooks[index];
// 更新状态的函数
const setState = (newValue) => {
if (typeof newValue === ‘function’) {
hook.state = newValue(hook.state);
} else {
hook.state = newValue;
}
// 触发重新渲染
component.render();
};
hookIndex++;
return [hook.state, setState];
}
function useEffect(callback, deps) {
const component = currentComponent;
const index = hookIndex;
const hook = component.hooks[index] || {
deps: undefined,
cleanup: null
};
// 检查依赖是否变化
const depsChanged = !deps ||
!hook.deps ||
deps.some((dep, i) => dep !== hook.deps[i]);
if (depsChanged) {
// 执行清理函数(如果存在)
if (hook.cleanup) {
hook.cleanup();
}
// 执行副作用
hook.cleanup = callback();
hook.deps = deps;
}
component.hooks[index] = hook;
hookIndex++;
}
// 模拟组件
class Component {
constructor(props) {
this.props = props;
this.hooks = [];
this.state = {};
}
render() {
// 重置hook索引
hookIndex = 0;
currentComponent = this;
// 调用用户定义的render方法
const element = this._render();
currentComponent = null;
return element;
}
_render() {
// 这里应该由子类实现
return null;
}
}
// 使用示例
class MyComponent extends Component {
_render() {
const [count, setCount] = useState(0);
const [name, setName] = useState(‘React’);
useEffect(() => {
console.log(`Count changed to: ${count}`);
return () => console.log(‘Cleanup’);
}, [count]);
return {
type: ‘div’,
props: {
children: [
`Count: ${count}`,
`Name: ${name}`,
{
type: ‘button’,
props: {
onClick: () => setCount(c => c + 1),
children: ‘Increment’
}
}
]
}
};
}
}
// 测试
const myComponent = new MyComponent();
console.log(myComponent.render()); // 初始渲染
myComponent.render(); // 重新渲染
技巧总结
:
使用闭包保存状态
维护hook索引确保顺序一致性
依赖数组比较实现useEffect的优化
理解函数式更新(setState with function)的重要性
1.2 手写高阶组件(HOC)
题目
:请手写一个高阶组件,为组件添加loading状态管理。
解析
:HOC是React中重要的模式,考察对组件复用和组合的理解。
代码实现
:
import React from ‘react’;
// 高阶组件:添加loading状态
function withLoading(WrappedComponent) {
// 返回新的组件类
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
data: null,
error: null
};
}
// 模拟数据加载
loadData = async (url) => {
this.setState({ isLoading: true, error: null });
try {
const response = await fetch(url);
const data = await response.json();
this.setState({
isLoading: false,
data,
error: null
});
return data;
} catch (error) {
this.setState({
isLoading: false,
data: null,
error: error.message
});
throw error;
}
}
render() {
const { isLoading, data, error } = this.state;
// 注入额外的props
const injectedProps = {
loading: isLoading,
loadData: this.loadData,
apiData: data,
apiError: error
};
return (
}
{error &&
}
);
}
};
}
// 使用示例
const UserProfile = ({ name, email, loading, loadData, apiData }) => {
return (
{name}
{email}
{apiData && (
API数据:
{JSON.stringify(apiData, null, 2)}
)}
);
};
// 应用高阶组件
const UserProfileWithLoading = withLoading(UserProfile);
// 在应用中使用
function App() {
return
}
技巧总结
:
HOC应该保持纯函数,不修改原组件
正确传递props,避免props丢失
考虑displayName等静态属性的传递
处理多个HOC组合时的顺序问题
1.3 手写受控组件与非受控组件
题目
:分别实现受控组件和非受控组件的表单处理。
解析
:这是React表单处理的核心概念,必须熟练掌握。
代码实现
:
// 受控组件示例
class ControlledForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: ”,
email: ”,
password: ”,
errors: {}
};
}
handleChange = (e) => {
const { name, value } = e.target;
this.setState({ [name]: value });
// 实时验证
if (name === ’email’) {
this.validateEmail(value);
}
}
validateEmail = (email) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
this.setState(prev => ({
errors: { …prev.errors, email: ‘无效的邮箱格式’ }
}));
} else {
this.setState(prev => ({
errors: { …prev.errors, email: ” }
}));
}
}
handleSubmit = (e) => {
e.preventDefault();
const { username, email, password } = this.state;
// 提交前的验证
if (!username || !email || !password) {
alert(‘请填写所有字段’);
return;
}
console.log(‘提交数据:’, { username, email, password });
// 发送请求…
}
render() {
const { username, email, password, errors } = this.state;
return (
);
}
}
// 非受控组件示例
class UncontrolledForm extends React.Component {
constructor(props) {
super(props);
this.usernameRef = React.createRef();
this.emailRef = React.createRef();
this.passwordRef = React.createRef();
}
handleSubmit = (e) => {
e.preventDefault();
// 在提交时获取DOM节点的值
const username = this.usernameRef.current.value;
const email = this.emailRef.current.value;
const password = this.passwordRef.current.value;
if (!username || !email || !password) {
alert(‘请填写所有字段’);
return;
}
console.log(‘提交数据:’, { username, email, password });
// 发送请求…
// 可以重置表单
e.target.reset();
}
render() {
return (
);
}
}
// 函数式组件中的非受控组件(使用useRef)
function UncontrolledFunctionalForm() {
const usernameRef = React.useRef(null);
const emailRef = React.useRef(null);
const passwordRef = React.useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
const username = usernameRef.current.value;
const email = emailRef.current.value;
const password = passwordRef.current.value;
console.log(‘提交数据:’, { username, email, password });
};
return (
);
}
技巧总结
:
受控组件:状态驱动,适合需要实时验证和复杂交互的场景
非受控组件:DOM驱动,适合简单表单或集成第三方库
合理选择使用场景,避免过度复杂化
二、React Hooks手写题
2.1 手写自定义Hook:useFetch
题目
:请手写一个useFetch Hook,处理异步数据获取。
解析
:考察对自定义Hook的理解,以及错误处理、加载状态管理等实际问题。
代码实现
:
import { useState, useEffect, useCallback, useRef } from ‘react’;
// 自定义Hook:useFetch
function useFetch(url, options = {}) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// 使用useRef来追踪组件是否挂载,避免内存泄漏
const isMounted = useRef(true);
// 使用useCallback优化,避免每次渲染都创建新函数
const fetchData = useCallback(async () => {
if (!url) return;
setLoading(true);
setError(null);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (isMounted.current) {
setData(result);
}
} catch (err) {
if (isMounted.current) {
setError(err.message);
}
} finally {
if (isMounted.current) {
setLoading(false);
}
}
}, [url, options]);
useEffect(() => {
isMounted.current = true;
fetchData();
// 清理函数
return () => {
isMounted.current = false;
};
}, [fetchData]);
// 提供手动重新加载的功能
const refetch = useCallback(() => {
fetchData();
}, [fetchData]);
return { data, loading, error, refetch };
}
// 使用示例:用户列表组件
function UserList() {
const { data: users, loading, error, refetch } = useFetch(‘https://jsonplaceholder.typicode.com/users’);
if (loading) return
;
if (error) return
;
return (
用户列表
-
{users && users.map(user => (
- {user.name} – {user.email}
))}
);
}
// 高级版本:支持取消请求
function useFetchWithCancel(url, options = {}) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const controllerRef = useRef(null);
const fetchData = useCallback(async () => {
// 取消之前的请求
if (controllerRef.current) {
controllerRef.current.abort();
}
// 创建新的AbortController
controllerRef.current = new AbortController();
setLoading(true);
setError(null);
try {
const response = await fetch(url, {
…options,
signal: controllerRef.current.signal
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
if (err.name !== ‘AbortError’) {
setError(err.message);
}
} finally {
setLoading(false);
}
}, [url, options]);
useEffect(() => {
fetchData();
return () => {
if (controllerRef.current) {
controllerRef.current.abort();
}
};
}, [fetchData]);
const refetch = useCallback(() => {
fetchData();
}, [fetchData]);
return { data, loading, error, refetch };
}
技巧总结
:
使用useRef追踪组件状态,避免内存泄漏
使用useCallback优化性能
提供手动重新加载功能
考虑请求取消机制
处理竞态条件(race conditions)
2.2 手写自定义Hook:useDebounce
题目
:请手写一个useDebounce Hook,用于防抖处理。
解析
:考察对闭包、定时器管理和Hook生命周期的理解。
代码实现
:
import { useState, useEffect, useRef } from ‘react’;
// 基础版本:防抖值
function useDebounce(value, delay = 500) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
// 设置定时器
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// 清理定时器
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
// 高级版本:防抖函数
function useDebouncedCallback(callback, delay = 500) {
const timeoutRef = useRef(null);
const callbackRef = useRef(callback);
// 更新回调引用
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
const debouncedFunction = (…args) => {
// 清理之前的定时器
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// 设置新的定时器
timeoutRef.current = setTimeout(() => {
callbackRef.current(…args);
}, delay);
};
// 清理函数
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return debouncedFunction;
}
// 使用示例:搜索框
function SearchComponent() {
const [searchTerm, setSearchTerm] = useState(”);
const [results, setResults] = useState([]);
// 防抖的搜索值
const debouncedSearchTerm = useDebounce(searchTerm, 500);
useEffect(() => {
if (debouncedSearchTerm) {
// 模拟API搜索
console.log(‘执行搜索:’, debouncedSearchTerm);
// 实际项目中这里调用API
setResults([`结果1: ${debouncedSearchTerm}`, `结果2: ${debouncedSearchTerm}`]);
} else {
setResults([]);
}
}, [debouncedSearchTerm]);
return (
placeholder=”搜索…”
/>
))}
);
}
// 使用示例:窗口大小调整监听
function ResizeListener() {
const [windowSize, setWindowSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});
const handleResize = useDebouncedCallback(() => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight
});
}, 250);
useEffect(() => {
window.addEventListener(‘resize’, handleResize);
return () => window.removeEventListener(‘resize’, handleResize);
}, [handleResize]);
return (
);
}
技巧总结
:
使用useRef保存定时器ID,避免闭包陷阱
正确的清理逻辑防止内存泄漏
区分防抖值和防抖函数的使用场景
考虑延迟时间的可配置性
2.3 手写自定义Hook:useLocalStorage
题目
:请手写一个useLocalStorage Hook,实现状态与localStorage的同步。
解析
:考察对浏览器API、状态管理和Hook副作用的综合运用。
代码实现
:
import { useState, useEffect, useCallback } from ‘react’;
// 自定义Hook:useLocalStorage
function useLocalStorage(key, initialValue) {
// 使用函数式初始化,避免重复计算
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn(`Error reading localStorage key “${key}”:`, error);
return initialValue;
}
});
// 封装setValue,处理localStorage同步
const setValue = useCallback((value) => {
try {
// 允许函数式更新
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
// 保存到localStorage
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.warn(`Error setting localStorage key “${key}”:`, error);
}
}, [key, storedValue]);
// 监听localStorage变化(跨标签页同步)
useEffect(() => {
const handleStorageChange = (e) => {
if (e.key === key) {
try {
const newValue = e.newValue ? JSON.parse(e.newValue) : initialValue;
setStoredValue(newValue);
} catch (error) {
console.warn(`Error parsing localStorage value for key “${key}”:`, error);
}
}
};
window.addEventListener(‘storage’, handleStorageChange);
return () => {
window.removeEventListener(‘storage’, handleStorageChange);
};
}, [key, initialValue]);
return [storedValue, setValue];
}
// 使用示例:主题切换
function ThemeSwitcher() {
const [theme, setTheme] = useLocalStorage(‘theme’, ‘light’);
useEffect(() => {
document.body.className = `theme-${theme}`;
}, [theme]);
return (
当前主题: {theme}
);
}
// 使用示例:表单持久化
function PersistentForm() {
const [formData, setFormData] = useLocalStorage(‘form_data’, {
name: ”,
email: ”,
message: ”
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
…prev,
[name]: value
}));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(‘提交数据:’, formData);
// 提交后清空
setFormData({ name: ”, email: ”, message: ” });
};
return (
);
}
// 增强版本:支持过期时间
function useLocalStorageWithExpiry(key, initialValue, expiryMinutes = 60) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
if (!item) return initialValue;
const { value, expiry } = JSON.parse(item);
if (new Date().getTime() > expiry) {
window.localStorage.removeItem(key);
return initialValue;
}
return value;
} catch (error) {
return initialValue;
}
});
const setValue = useCallback((value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
const expiry = new Date().getTime() + expiryMinutes * 60 * 1000;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify({
value: valueToStore,
expiry
}));
} catch (error) {
console.error(‘LocalStorage error:’, error);
}
}, [key, storedValue, expiryMinutes]);
return [storedValue, setValue];
}
技巧总结
:
处理JSON解析异常
考虑跨标签页同步(storage事件)
支持函数式更新
处理SSR场景(window未定义)
考虑数据过期机制
三、React性能优化手写题
3.1 手写React.memo和useMemo模拟
题目
:请手写一个简化的React.memo和useMemo实现。
解析
:考察对React性能优化机制的理解,包括浅比较、依赖数组等。
代码实现
:
// 模拟React.memo
function memo(Component, areEqual = shallowEqual) {
const MemoizedComponent = (props) => {
const prevProps = useRef(props);
// 比较props变化
if (!areEqual(prevProps.current, props)) {
prevProps.current = props;
}
return Component(prevProps.current);
};
MemoizedComponent.displayName = `Memo(${Component.displayName || Component.name || ‘Component’})`;
return MemoizedComponent;
}
// 浅比较函数
function shallowEqual(obj1, obj2) {
if (obj1 === obj2) return true;
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
for (let key of keys1) {
if (obj1[key] !== obj2[key]) return false;
}
return true;
}
// 模拟useMemo
function useMemo(factory, deps) {
const memoizedRef = useRef({
value: null,
deps: null,
factory: null
});
const memoized = memoizedRef.current;
// 检查依赖是否变化
const depsChanged = !deps ||
!memoized.deps ||
deps.some((dep, i) => dep !== memoized.deps[i]);
if (depsChanged) {
// 重新计算
memoized.value = factory();
memoized.deps = deps;
memoized.factory = factory;
}
return memoized.value;
}
// 使用示例:昂贵的计算
function ExpensiveComponent({ list, threshold }) {
// 使用useMemo优化昂贵的计算
const filteredList = useMemo(() => {
console.log(‘执行昂贵的过滤计算…’);
return list.filter(item => item.value > threshold);
}, [list, threshold]);
// 使用memo优化子组件渲染
const ListItem = memo(({ item }) => {
console.log(‘渲染ListItem:’, item.id);
return
;
});
return (
过滤结果 ({filteredList.length})
{filteredList.map(item => (
))}
);
}
// 测试数据
const testData = Array.from({ length: 1000 }, (_, i) => ({
id: i,
name: `Item ${i}`,
value: Math.random() * 100
}));
// 使用示例
function App() {
const [threshold, setThreshold] = useState(50);
return (
/>
阈值: {threshold}
);
}
技巧总结
:
理解浅比较的原理和局限性
正确处理依赖数组
避免在useMemo中创建新对象
考虑自定义比较函数
3.2 手写虚拟滚动(Virtual Scrolling)
题目
:请手写一个简化的虚拟滚动实现。
解析
:考察对性能优化、DOM操作和计算几何的理解。
代码实现
:
import React, { useState, useRef, useEffect, useMemo } from ‘react’;
// 虚拟滚动组件
function VirtualList({ items, itemHeight, containerHeight, renderItem }) {
const [scrollTop, setScrollTop] = useState(0);
const containerRef = useRef(null);
// 计算可见范围
const visibleRange = useMemo(() => {
const startIndex = Math.floor(scrollTop / itemHeight);
const visibleCount = Math.ceil(containerHeight / itemHeight);
const endIndex = Math.min(startIndex + visibleCount + 2, items.length); // +2 for buffer
return { startIndex, endIndex };
}, [scrollTop, itemHeight, containerHeight, items.length]);
// 计算总高度
const totalHeight = items.length * itemHeight;
// 计算偏移量
const offsetY = visibleRange.startIndex * itemHeight;
// 可见项
const visibleItems = items.slice(visibleRange.startIndex, visibleRange.endIndex);
// 处理滚动事件
const handleScroll = (e) => {
setScrollTop(e.target.scrollTop);
};
// 滚动到指定索引
const scrollToIndex = (index) => {
if (containerRef.current) {
containerRef.current.scrollTop = index * itemHeight;
}
};
return (
{/* 占位元素,撑开容器高度 */}
{visibleItems.map((item, index) => (
{renderItem(item, visibleRange.startIndex + index)}
))}
{/* 滚动控制按钮 */}
);
}
// 使用示例
function VirtualScrollExample() {
// 生成10000条数据
const items = useMemo(() =>
Array.from({ length: 10000 }, (_, i) => ({
id: i,
name: `Item ${i}`,
value: Math.random().toFixed(2)
})), []
);
const renderItem = (item, index) => (
{item.name} – 值: {item.value}
);
return (
虚拟滚动列表 (10000 items)
);
}
// 优化版本:支持动态高度
function DynamicVirtualList({ items, estimatedHeight, containerHeight, renderItem }) {
const [scrollTop, setScrollTop] = useState(0);
const [heights, setHeights] = useState({});
const containerRef = useRef(null);
// 计算累计高度
const cumulativeHeights = useMemo(() => {
const result = [0];
let total = 0;
for (let i = 0; i < items.length; i++) {
const height = heights[i] || estimatedHeight;
total += height;
result.push(total);
}
return result;
}, [items, heights, estimatedHeight]);
// 二分查找可见范围
const visibleRange = useMemo(() => {
if (items.length === 0) return { startIndex: 0, endIndex: 0 };
// 查找起始索引
let low = 0, high = items.length – 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (cumulativeHeights[mid] < scrollTop) {
low = mid + 1;
} else {
high = mid - 1;
}
}
const startIndex = Math.max(0, high);
// 查找结束索引
const targetBottom = scrollTop + containerHeight;
low = startIndex;
high = items.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (cumulativeHeights[mid] < targetBottom) {
low = mid + 1;
} else {
high = mid - 1;
}
}
const endIndex = Math.min(items.length, low + 2);
return { startIndex, endIndex };
}, [scrollTop, containerHeight, cumulativeHeights, items.length]);
const totalHeight = cumulativeHeights[items.length];
const offsetY = cumulativeHeights[visibleRange.startIndex];
const visibleItems = items.slice(visibleRange.startIndex, visibleRange.endIndex);
const handleScroll = (e) => {
setScrollTop(e.target.scrollTop);
};
const measureHeight = (index, element) => {
if (element && !heights[index]) {
const height = element.getBoundingClientRect().height;
setHeights(prev => ({ …prev, [index]: height }));
}
};
return (
{visibleItems.map((item, index) => {
const actualIndex = visibleRange.startIndex + index;
return (
style={{
minHeight: `${estimatedHeight}px`,
padding: ’10px’,
borderBottom: ‘1px solid #eee’
}}
>
{renderItem(item, actualIndex)}
);
})}
);
}
技巧总结
:
使用绝对定位和偏移量控制可见区域
实现缓冲区域(buffer)避免快速滚动空白
考虑动态高度的实现(二分查找)
处理滚动锚定(scroll anchoring)
优化事件处理,避免频繁重渲染
3.3 手写React.lazy和Suspense模拟
题目
:请手写一个简化的React.lazy和Suspense实现。
解析
:考察对代码分割、异步组件和错误边界的理解。
代码实现
:
import React, { useState, useEffect, Suspense } from ‘react’;
// 模拟React.lazy
function lazy(factory) {
let component = null;
let error = null;
let promise = null;
return function LazyComponent(props) {
const [loading, setLoading] = useState(!component);
useEffect(() => {
if (!component && !error) {
// 如果还没有组件且没有错误,开始加载
if (!promise) {
promise = factory()
.then(module => {
component = module.default || module;
})
.catch(err => {
error = err;
});
}
promise.then(() => {
setLoading(false);
});
}
}, []);
if (error) {
throw error; // 抛出错误,让ErrorBoundary捕获
}
if (loading) {
return null; // 或者返回loading UI
}
const Component = component;
return
};
}
// 模拟Suspense组件
class Suspense extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.log(‘Suspense caught error:’, error, errorInfo);
}
render() {
if (this.state.hasError) {
// 渲染fallback或错误UI
return this.props.fallback ||
;
}
return this.props.children;
}
}
// 模拟Suspense组件(函数式版本)
function SuspenseFunctional({ children, fallback }) {
const [isPending, setIsPending] = useState(false);
// 这里需要更复杂的实现来捕获子组件中的promise
// 简化版本:假设通过全局机制捕获
return isPending ? fallback : children;
}
// 使用示例:模拟组件加载
const LazyComponent = lazy(() =>
new Promise(resolve => {
setTimeout(() => {
resolve({
default: function HeavyComponent() {
return
;
}
});
}, 2000);
})
);
// 实际的懒加载组件(使用import)
const RealLazyComponent = React.lazy(() => import(‘./HeavyComponent’));
// 使用Suspense包裹
function App() {
return (
代码分割示例
}>
{/* 实际项目中这样使用 */}
{/*