简体   繁体   English

在 React.js 中使用带有 useState 的 Context API,有什么缺点吗?

[英]Using Context API with useState in React.js, any downsides?

I create a context and a provider as below.我创建了一个上下文和一个提供者,如下所示。 As you can see, I use useState() within my provider (for state) along with functions (all passed within an object as the value prop, allows for easy destructuring whatever I need in child components).如您所见,我在我的提供程序中使用 useState()(用于状态)以及函数(所有这些都在对象中作为值 prop 传递,允许轻松解构我在子组件中需要的任何内容)。

import React, { useState, createContext } from "react";

const CountContext = createContext(null);

export const CountProvider = ({ children }) => {
  const [count, setCount] = useState(0);

  const incrementCount = () => {
    setCount(count + 1);
  };

  const decrementCount = () => {
    setCount(count - 1);
  };

  return (
    <CountContext.Provider value={{ count, incrementCount, decrementCount }}>
      {children}
    </CountContext.Provider>
  );
};

export default CountContext;

I wrap my app within such a provider(s) at a higher location such as at index.js.我将我的应用程序包装在这样的提供程序中,位于更高的位置,例如 index.js。 And consume the state using useContext() as below.并使用 useContext() 消耗状态,如下所示。

import React, { useContext } from "react";
import CountContext from "../contexts/CountContext";
import Incrementer from "./Incrementer";
import Decrementer from "./Decrementer";

const Counter = () => {
  const { count } = useContext(CountContext);

  return (
    <div className="counter">
      <div className="count">{count}</div>
      <div className="controls">
        <Decrementer />
        <Incrementer />
      </div>
    </div>
  );
};

export default Counter;

Everything is working just fine, and I find it easier to maintain things this way as compared to some of the other methods of (shared) state management.一切都很好,我发现与其他一些(共享)状态管理方法相比,以这种方式维护事物更容易。

CodeSandbox: https://codesandbox.io/s/react-usecontext-simplified-consumption-hhfz6 CodeSandbox: https ://codesandbox.io/s/react-usecontext-simplified-consumption-hhfz6

I am wondering if there is a fault or flaw here that I haven't noticed yet?我想知道这里是否有我还没有注意到的故障或缺陷?

One of the key differences with other state management tools like Redux is performance .与 Redux 等其他状态管理工具的主要区别之一是性能

Any child that uses a Context needs to be nested inside the ContextProvider component.任何使用 Context 的子项都需要嵌套在ContextProvider组件中。 Every time the ContextProvider state changes it will render, and all its (non-memoized) children will render too.每次ContextProvider状态更改时,它都会呈现,并且它的所有(非记忆化)子项也会呈现。

In contrast, when using Redux we connect each Component to the store, so each component will render only if the part of the state it is connect to changes.相比之下,当使用 Redux 时,我们将每个组件连接到商店,因此每个组件只有在它连接到的状态部分发生变化时才会呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM