首页 > 解决方案 > 是否有可能摆脱每次重新渲染的 useContext 计算?

问题描述

我们可以使用空数组作为钩子中的第二个参数来防止对 useEffect 进行不必要的计算:

// that will be calculated every single re-rendering
useEffect(() => {...some procedures...})
// that will be calculated only after the first render
useEffect(() => {...some procedures...}, [])

但是,对于我们不能像上面那样做的 useContext 钩子,提供第二个参数。还有,我们不能用useCallback、useMemo来包装useContext。例如,我们有一个组件:

const someComponent = () => {

  const contextValue = useContext(SomeContext);

  const [inputValue, setInputValue] = useState('');

  return (
    <Fragment>
      <input value={inputValue} onChange={onInputChange} />
      <span>{contextValue}</span>
    </Fragment>
  )

问题是每次输入都会重新渲染,我们每次都会有不必要的 useContext 重新渲染。决定之一是在两个方面制动组件:

const WithContextDataComponent = () => {

  const contextValue = useContext(SomeContext);

  return <JustInputComponent contextValue={contextValue} />

const JustInputComponent = (props) => {

  const [inputValue, setInputValue] = useState('');

  return <input value={inputValue} onChange={onInputChange} />

所以,现在问题消失了,但是我们有两个组件。而在上面的组件中,<SomeComponent />我们应该 import <WithContextDataComponent />,我认为这有点难看。

我可以在不拆分为两个组件的情况下停止不必要的 useContext 重新渲染吗?

标签: reactjsreact-hooks

解决方案


来自 React Hooks API 参考:

https://reactjs.org/docs/hooks-reference.html#usecontext

使用上下文

const value = useContext(MyContext);

接受一个上下文对象(从 React.createContext 返回的值)并返回该上下文的当前上下文值。当前上下文值由树中调用组件上方最近的值 prop 确定。

当最近的组件更新时,此 Hook 将触发重新渲染,并将最新的上下文值传递给该 MyContext 提供程序。

正如您从文档中看到的那样,如果useContext()钩子提供的值在某些时候发生变化,钩子只会导致重新渲染您的组件。Ans 这可能是您的预期行为。为什么在上下文挂钩中需要陈旧数据?

当您的组件自行重新渲染时,上下文不发生变化,该useContext()行将简单地返回与之前渲染相同的值。

看来您正在使用useContext()钩子的方式来使用它。我看不出有什么问题。


推荐阅读