React 中常见的Hooks,安排!

哈喽小伙伴们大家好!我是小李,今天是年后开工的第一天,相信大家已经元气满满,准备好迎接新的一年的挑战了吧!打起精神来,我们继续加油呀!今天,给大家分享一道我之前面试被问到相关Hooks的一道题目,今天先来说说react的,下期文章为大家分享vue的,希望对大家有所帮助!

首先,什么是Hooks?为什么会有Hooks这个东西?

所谓Hooks,它其实就是一些特殊的函数,也称钩子函数,它允许开发者在不编写 class 的情况下使用 state 以及其他 React 特性。简单来说,Hooks 就是一些特殊的函数,这些函数可以让你 "钩入"(Hook into) React 的状态和生命周期等特性。

1、useState

用于在函数组件中添加 statestate 是 React 组件中的一个重要概念,它允许组件存储和管理动态数据。

复制代码
import React, { useState } from 'react';

function Counter() {

    const [count, setCount] = useState(0);

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

export default Counter;
2、useEffect

用于处理副作用操作,比如数据获取、订阅、手动修改 DOM 等。它类似于 componentDidMountcomponentDidUpdatecomponentWillUnmount 这几个生命周期方法的组合。

复制代码
import React, { useState, useEffect } from 'react';

function Example() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        // 更新文档标题
        document.title = `You clicked ${count} times`;
    });

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

export default Example;
3、useContext

用于在组件之间共享数据,避免通过中间组件层层传递 props。它需要和 React.createContext 一起使用。

复制代码
import React, { createContext, useContext, useState } from 'react';

// 创建一个 Context 对象
const ThemeContext = createContext();

function App() {
    const [theme, setTheme] = useState('light');

    return (
        <ThemeContext.Provider value={theme}>
            <Toolbar />
            <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
                Toggle Theme
            </button>
        </ThemeContext.Provider>
    );
}

function Toolbar() {
    return (
        <div>
            <ThemedButton />
        </div>
    );
}

function ThemedButton() {
    // 使用 useContext 获取 ThemeContext 的值
    const theme = useContext(ThemeContext);
    return <button style={
  
  { background: theme === 'light' ? 'white' : 'black', color: theme === 'light' ? 'black' : 'white' }}>
        Themed Button
    </button>;
}

export default App;

接下来是一些不常见的。

1、useReducer

useState 的替代方案,适用于复杂的 state 逻辑或多个子值需要更新的情况。它使用一个reducer 函数来管理 state 的更新。

复制代码
import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return { count: state.count + 1 };
        case 'decrement':
            return { count: state.count - 1 };
        default:
            throw new Error();
    }
}

function Counter() {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (
        <>
            Count: {state.count}
            <button onClick={() => dispatch({ type: 'increment' })}>+</button>
            <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
        </>
    );
}

export default Counter;
2、useCallback

返回一个 memoized 回调函数,用于优化性能。当父组件重新渲染时,使用 useCallback 可以避免子组件因为传入的回调函数引用变化而不必要地重新渲染。

复制代码
import React, { useState, useCallback } from 'react';

function Parent() {
    const [count, setCount] = useState(0);

    // 使用 useCallback 缓存回调函数
    const handleClick = useCallback(() => {
        console.log('Button clicked');
    }, []);

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
            <Child onClick={handleClick} />
        </div>
    );
}

function Child({ onClick }) {
    return <button onClick={onClick}>Click me</button>;
}

export default Parent;
3、useMemo

返回一个 memoized 值,用于优化性能。它会在依赖项发生变化时重新计算值,避免在每次渲染时都进行昂贵的计算。

复制代码
import React, { useState, useMemo } from 'react';

function App() {
    const [a, setA] = useState(1);
    const [b, setB] = useState(2);

    // 使用 useMemo 缓存计算结果
    const sum = useMemo(() => {
        console.log('Calculating sum...');
        return a + b;
    }, [a, b]);

    return (
        <div>
            <p>a: {a}</p>
            <p>b: {b}</p>
            <p>Sum: {sum}</p>
            <button onClick={() => setA(a + 1)}>Increment a</button>
            <button onClick={() => setB(b + 1)}>Increment b</button>
        </div>
    );
}

export default App;
4、useRef

返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数。它可以用来访问 DOM 节点或在多次渲染之间保存值。

复制代码
import React, { useRef } from 'react';

function TextInputWithFocusButton() {
    const inputEl = useRef(null);
    const onButtonClick = () => {
        // `current` 指向已挂载到 DOM 上的文本输入元素
        inputEl.current.focus();
    };
    return (
        <>
            <input ref={inputEl} type="text" />
            <button onClick={onButtonClick}>Focus the input</button>
        </>
    );
}

export default TextInputWithFocusButton;

好啦,今天的分享就到这里,整理不易,如果觉得对你有帮助,欢迎给个三连支持,我是小李,我们下期见!

相关推荐
万少3 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站5 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名7 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫8 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊8 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter8 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折8 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_8 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码18 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial8 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js