React Hooks

Hook 是什么

Hook 是 React 团队在 React 16.8 版本中提出的新特性,在遵循函数式组件的前提下,为已知的 React 概念提供了更直接的 API:props,state,context,refs 以及声明周期,目的在于解决常年以来在 class 组件中存在的各种问题,实现更高效的编写 react 组件。


class 组件的不足

Redux 的作者 Dan Abramov 总结了组件类的几个缺点。

  • 大型组件很难拆分和重构,也很难测试。
  • 业务逻辑分散在组件的各个方法之中,导致重复逻辑或关联逻辑。
  • 组件类引入了复杂的编程模式,比如 render props 和高阶组件。

Hook 的优势

  • Hook 使你在无需改变组件结构的情况下复用状态逻辑(自定义 Hook)。
  • Hook 将组件中互相关联的部分拆分成更小的函数(比如设置订阅或请求数据)。
  • Hook 使你在非 class 的情况下可以使用更多的 React 特性。

Hook 使用规则

Hook 就是 Javascript 函数,使用它们时有两个额外的规则:

  • 只能在函数外层调用 Hook,不要在循环、条件判断或者子函数中调用。
  • 只能在 React 的函数组件和自定义 Hook 中调用 Hook。不要在其他 JavaScript 函数中调用。

在组件中 React 是通过判断 Hook 调用的顺序来判断某个 state 对应的 useState的,所以必须保证 Hook 的调用顺序在多次渲染之间保持一致,React 才能正确地将内部 state 和对应的 Hook 进行关联。

下面介绍 React 默认提供的几个最常用的钩子。


useState

useState 用于在函数组件中调用给组件添加一些内部状态 state,正常情况下纯函数不能存在状态副作用,通过调用该 Hook 函数可以给函数组件注入状态 state。
useState 唯一的参数就是初始 state,会返回当前状态和一个状态更新函数,并且 useState 返回的状态更新函数不会把新的 state 和旧的 state 进行合并,如需合并可使用 ES6 的对象结构语法进行手动合并。

基本使用

import React, { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <button onClick={() => setCount(count - 1)}>-</button>
      <input type="text" value={count} onChange={(e) => setCount(e.target.value)} />
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}

函数式更新

如果新的 state 需要通过使用先前的 state 计算得出,可以往 setState 传递函数,该函数将接收先前的 state,并返回一个更新后的值。

import React, { useState } from 'react'

export default function Counter() {
  const [count, setCount] = useState(0);

  const lazyAdd = () => {
    setTimeout(() => {
      // 每次执行都会最新的state,而不是使用事件触发时的state
      setCount(count => count + 1);
    }, 3000);
  } 

  return (
    <div>
      <p>the count now is {count}</p>
      <button onClick={() => setCount(count + 1)}>add</button>
      <button onClick={lazyAdd}>lazyAdd</button>
    </div>
  );
}

惰性初始 state

如果初始 state 需要通过复杂计算获得,则可以传入一个函数,在函数中计算并返回初始的 state,此函数只会在初始渲染时被调用。

import React, { useState } from 'react'

export default function Counter(props) {
  // 函数只在初始渲染时执行一次,组件重新渲染时该函数不会重新执行
  const initCounter = () => {
    console.log('initCounter');
    return { number: props.number };
  };
  const [counter, setCounter] = useState(initCounter);

  return (
    <div>
      <button onClick={() => setCounter({ number: counter.number - 1 })}>-</button>
      <input type="text" value={counter.number} onChange={(e) => setCounter({ number: e.target.value})} />
      <button onClick={() => setCounter({ number: counter.number + 1 })}>+</button>
    </div>
  );
}

跳过 state 更新

调用 State Hook 的更新函数时,React 将使用 Object.is 来比较前后两次 state,如果返回结果为 true,React 将跳过子组件的渲染及 effect 的执行。

import React, { useState } from 'react';

export default function Counter() {
  console.log('render Counter');
  const [counter, setCounter] = useState({
    name: '计时器',
    number: 0
  });

  // 修改状态时传的状态值没有变化,则不重新渲染
  return (
    <div>
      <p>{counter.name}: {counter.number}</p>
      <button onClick={() => setCounter({ ...counter, number: counter.number + 1})}>+</button>
      <button onClick={() => setCounter(counter)}>++</button>
    </div>
  );
}

useEffect

在函数组件主体内(React 渲染阶段)改变 DOM、添加订阅、设置定时器、记录日志以及执行其他包含副作用的操作都是不被允许的,因为这可能会产生莫名其妙的 bug 并破坏 UI 的一致性。
useEffect Hook 的使用则是用于完成此类副作用操作。useEffect 接收一个包含命令式、且可能有副作用代码的函数。
useEffect函数会在浏览器完成布局和绘制之后,下一次重新渲染之前执行,保证不会阻塞浏览器对屏幕的更新。

基本使用

import React, { useState, useEffect } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  // useEffect 内的回调函数会在初次渲染后和更新完成后执行
  // 相当于 componentDidMount 和 componentDidUpdate
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>count now is {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}

清除 effect

通常情况下,组件卸载时需要清除 effect 创建的副作用操作,useEffect Hook 函数可以返回一个清除函数,清除函数会在组件卸载前执行。组件在多次渲染中都会在执行下一个 effect 之前,执行该函数进行清除上一个 effect。
清除函数的执行时机类似于 class 组件componentDidUnmount 生命周期,这的话使用 useEffect 函数可以将组件中互相关联的部分拆分成更小的函数,防止遗忘导致不必要的内存泄漏。

import React, { useState, useEffect } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('start an interval timer')
    const timer = setInterval(() => {
      setCount((count) => count + 1);
    }, 1000);
    // 返回一个清除函数,在组件卸载前和下一个effect执行前执行
    return () => {
      console.log('destroy effect');
      clearInterval(timer);
    };
  }, []);

  return (
    <div>
      <p>count now is {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}

优化 effect 执行

默认情况下,effect 会在每一次组件渲染完成后执行。useEffect 可以接收第二个参数,它是 effect 所依赖的值数组,这样就只有当数组值发生变化才会重新创建订阅。但需要注意的是:

  • 确保数组中包含了所有外部作用域中会发生变化且在 effect 中使用的变量。
  • 传递一个空数组作为第二个参数可以使 effect 只会在初始渲染完成后执行一次。
import React, { useState, useEffect } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]); // 仅在 count 更改时更新

  return (
    <div>
      <p>count now is {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}

useContext

Context 提供了一个无需为每层组件手动添加 props ,就能在组件树间进行数据传递的方法,useContext 用于函数组件中订阅上层 context 的变更,可以获取上层 context 传递的 value prop 值。
useContext 接收一个 context 对象(React.createContext的返回值)并返回 context 的当前值,当前的 context 值由上层组件中距离当前组件最近的 的 value prop 决定。

基本使用

import React, { useContext, useState } from 'react';

const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

// 为当前 theme 创建一个 context
const ThemeContext = React.createContext();

export default function Toolbar(props) {
  const [theme, setTheme] = useState(themes.dark);

  const toggleTheme = () => {
    setTheme(currentTheme => (
      currentTheme === themes.dark
        ? themes.light
        : themes.dark
    ));
  };

  return (
    // 使用 Provider 将当前 props.value 传递给内部组件
    <ThemeContext.Provider value={{theme, toggleTheme}}>
      <ThemeButton />
    </ThemeContext.Provider>
  );
}

function ThemeButton() {
  // 通过 useContext 获取当前 context 值
  const { theme, toggleTheme } = useContext(ThemeContext);
  
  return (
    <button style={{background: theme.background, color: theme.foreground }} onClick={toggleTheme}>
      Change the button's theme
    </button>
  );
}

优化消费 context 组件

调用了 useContext 的组件都会在 context 值变化时重新渲染,为了减少重新渲染组件的较大开销,可以通过使用 memoization 来优化。
假设由于某种原因,您有 AppContext,其值具有 theme 属性,并且您只想在 appContextValue.theme 更改上重新渲染一些 ExpensiveTree。

方式1: 拆分不会一起更改的 context

function Button() {
  // 把 theme context 拆分出来,其他 context 变化时不会导致 ExpensiveTree 重新渲染
  let theme = useContext(ThemeContext);
  return <ExpensiveTree className={theme} />;
}

方式2:当不能拆分 context 时,将组件一分为二,给中间组件加上 React.memo

function Button() {
  let appContextValue = useContext(AppContext);
  let theme = appContextValue.theme; // 获取 theme 属性
  return <ThemedButton theme={theme} />
}

const ThemedButton = memo(({ theme }) => {
  // 使用 memo 尽量复用上一次渲染结果
  return <ExpensiveTree className={theme} />;
});

方式3:返回一个内置 useMemo 的组件

function Button() {
  let appContextValue = useContext(AppContext);
  let theme = appContextValue.theme; // 获取 theme 属性

  return useMemo(() => {
    // The rest of your rendering logic
    return <ExpensiveTree className={theme} />;
  }, [theme])
}

useReducer

useReducer 作为 useState 的代替方案,在某些场景下使用更加适合,例如 state 逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等。
使用 useReducer 还能给那些会触发深更新的组件做性能优化,因为父组件可以向自组件传递 dispatch 而不是回调函数。

基本使用

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();
  }
}

export default function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

初始化 state

useReducer 初始化 sate 的方式有两种

// 方式1
const [state, dispatch] = useReducer(
	reducer,
  {count: initialCount}
);

// 方式2
function init(initialClunt) {
  return {count: initialClunt};
}
const [state, dispatch] = useReducer(reducer, initialCount, init);

useRef

useRef 用于返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。
useRef 创建的 ref 对象就是一个普通的 JavaScript 对象,而 useRef() 和自建一个 {current: …} 对象的唯一区别是,useRef 会在每次渲染时返回同一个 ref 对象。

const refContainer = useRef(initialValue);

绑定 DOM 元素

使用 useRef 创建的 ref 对象可以作为访问 DOM 的方式,将 ref 对象以
形式传入组件,React 会在组件创建完成后会将 ref 对象的 .current 属性设置为相应的 DOM 节点。

import React, { useRef } from 'react'

export default function FocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    inputEl.current.focus();
  };

  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

绑定可变值

useRef 创建的 ref 对象同时可以用于绑定任何可变值,通过手动给该对象的.current 属性设置对应的值即可。

import React, { useState, useRef, useEffect } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  const currentCount = useRef();
  // 使用 useEffect 获取当前 count
  useEffect(() => {
    currentCount.current = count;
  }, [count]);

  const alertCount = () => {
    setTimeout(() => {
      alert(`Current count is: ${currentCount.current}, Real count is: ${count}`);
    }, 3000);
  }

  return (
    <>
      <p>count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Count add</button>
      <button onClick={alertCount}>Alert current Count</button>
    </>
  );
}

性能优化(useCallback & useMemo)

useCallback 和 useMemo 结合 React.Memo 方法的使用是常见的性能优化方式,可以避免由于父组件状态变更导致不必要的子组件进行重新渲染

useCallback

useCallback 用于创建返回一个回调函数,该回调函数只会在某个依赖项发生改变时才会更新,可以把回调函数传递给经过优化的并使用引用相等性去避免非必要渲染的子组件,在 props 属性相同情况下,React 将跳过渲染组件的操作并直接复用最近一次渲染的结果。

import React, { useState, useCallback } from 'react';

function SubmitButton(props) {
  const { onButtonClick, children } = props;
  console.log(`${children} updated`);

  return (
    <button onClick={onButtonClick}>{children}</button>
  );
}
// 使用 React.memo 检查 props 变更,复用最近一次渲染结果
SubmitButton = React.memo(submitButton);

export default function CallbackForm() {
  const [count1, setCount1] = useState(0);
  const [count2, setCount2] = useState(0);

  const handleAdd1 = () => {
    setCount1(count1 + 1);
  }

  // 调用 useCallback 返回一个 memoized 回调,该回调在依赖项更新时才会更新
  const handleAdd2 = useCallback(() => {
    setCount2(count2 + 1);
  }, [count2]);

  return (
    <>
      <div>
        <p>count1: {count1}</p>
        <SubmitButton onButtonClick={handleAdd1}>button1</SubmitButton>
      </div>
      <div>
        <p>count2: {count2}</p>
        <SubmitButton onButtonClick={handleAdd2}>button2</SubmitButton>
      </div>
    </>
  )
}

useCallback(fn, deps) 相当于 useMemo(() => fn, deps),以上 useCallback 可替换成 useMemo 结果如下:

const handleAdd2 = useMemo(() => {
  return () => setCount2(count2 + 1);
}, [count2]);

useMemo

把“创建”函数和依赖项数组作为参数传入 useMemo,它仅会在某个依赖项改变时才重新计算 memoized 值。这种优化有助于避免在每次渲染时都进行高开销的计算。
使用注意:

  • 传入 useMemo 的函数会在渲染期间执行,不要在这个函数内部执行与渲染无关的操作。
  • 如果没有提供依赖项数组,useMemo 在每次渲染时都会计算新的值。
import React, { useState, useMemo } from 'react';

function counterText({ countInfo }) {
  console.log(`${countInfo.name} updated`);

  return (
    <p>{countInfo.name}: {countInfo.number}</p>
  );
}
// // 使用 React.memo 检查 props 变更,复用最近一次渲染结果
const CounterText = React.memo(counterText);

export default function Counter() {
  const [count1, setCount1] = useState(0);
  const [count2, setCount2] = useState(0);

  const countInfo1 = {
    name: 'count1',
    number: count1
  };
  // 使用 useMemo 缓存最近一次计算结果,会在依赖项改变时才重新计算
  const countInfo2 = useMemo(() => ({
    name: 'count2',
    number: count2
  }), [count2]);

  return (
    <>
      <div>
        <CounterText countInfo={countInfo1} />
        <button onClick={() => setCount1(count1 + 1)}>Add count1</button>
      </div>
      <div>
        <CounterText countInfo={countInfo2} />
        <button onClick={() => setCount2(count2 + 1)}>Add count2</button>
      </div>
    </>
  );
}

其他 Hook

useImperativeHandle

useImperativeHandle 可以让你在使用 ref 时自定义暴露给父组件的实例值。在大多数情况下,应当避免使用 ref 这样的命令式代码。useImperativeHandle 应当与 React.forwardRef 一起使用:

import React, { useRef, useImperativeHandle, useState } from 'react'

function FancyInput(props, ref) {
  const inputRef = useRef();
  // 自定义暴露给父组件的 ref 实例值
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} type="text" {...props} />;
}
// 通过 forwardRef 向父组件传递暴露的 ref
const ForwardFancyInput = React.forwardRef(FancyInput);

export default function Counter() {
  const [text, setText] = useState('');
  const inputRef = useRef();
  
  const onInputFocus = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <ForwardFancyInput ref={inputRef} value={text} onChange={e => setText(e.target.value)} />
      <button onClick={onInputFocus}>Input focus</button>
    </>
  );
}

useLayoutEffect

useLayoutEffect 与 useEffect 类似,与 useEffect 在浏览器 layout 和 painting 完成后异步执行 effect 不同的是,它会在浏览器布局 layout 之后,painting 之前同步执行 effect。
useLayoutEffect 的执行时机对比如下:

import React, { useState, useEffect, useLayoutEffect } from 'react';

export default function LayoutEffect() {
  const [width, setWidth] = useState('100px');

  // useEffect 会在所有 DOM 渲染完成后执行 effect 回调
  useEffect(() => {
    console.log('effect width: ', width);
  });
  // useLayoutEffect 会在所有的 DOM 变更之后同步执行 effect 回调
  useLayoutEffect(() => {
    console.log('layoutEffect width: ', width);
  });
  
  return (
    <>
      <div id='content' style={{ width, background: 'red' }}>内容</div>
      <button onClick={() => setWidth('100px')}>100px</button>
      <button onClick={() => setWidth('200px')}>200px</button>
      <button onClick={() => setWidth('300px')}>300px</button>
    </>
  );
}

// 使用 setTimeout 保证在组件第一次渲染完成后执行,获取到对应的 DOM
setTimeout(() => {
  const contentEl = document.getElementById('content');
  // 监视目标 DOM 结构变更,会在 useLayoutEffect 回调执行后,useEffect 回调执行前调用
  const observer = new MutationObserver(() => {
    console.log('content element layout updated');
  });
  observer.observe(contentEl, {
    attributes: true
  });
}, 1000);

自定义Hook

通过自定义 Hook,可以将组件逻辑提取到可重用的函数中,在 Hook 特性之前,React 中有两种流行的方式来共享组件之间的状态逻辑:render props和高阶组件,但此类解决方案会导致组件树的层级冗余等问题。而自定义 Hook 的使用可以很好的解决此类问题。

创建自定义 Hook

自定义 Hook 是一个函数,其名称以 “use” 开头,函数内部可以调用其他的 Hook。以下就是实时获取鼠标位置的自定义 Hook 实现:

import { useEffect, useState } from "react"

export const useMouse = () => {
  const [position, setPosition] = useState({
    x: null,
    y: null
  });

  useEffect(() => {
    const moveHandler = (e) => {
      setPosition({
        x: e.screenX,
        y: e.screenY
      });
    };

    document.addEventListener('mousemove', moveHandler);
    return () => {
      document.removeEventListener('mousemove', moveHandler);
    };
  }, []);

  return position;
}

使用自定义 Hook

自定义 Hook 的使用规则与 Hook 使用规则基本一致,以下是 useMouse 自定义 Hook 的使用过程:

import React from 'react';
import { useMouse } from '../hooks/useMouse';

export default function MouseMove() {
  const { x, y } = useMouse();
  return (
    <>
      <p>Move mouse to see changes</p>
      <p>x position: {x}</p>
      <p>y position: {y}</p>
    </>
  );
}

每次使用自定义 Hook 时,React 都会执行该函数来获取独立的 state 和执行独立的副作用函数,所有 state 和副作用都是完全隔离的。

    Captcha Code

    0 笔记

    分享笔记

    Inline Feedbacks
    View all notes