0

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).

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. And consume the state using useContext() as below.

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

I am wondering if there is a fault or flaw here that I haven't noticed yet?

1 Answer 1

1

One of the key differences with other state management tools like Redux is performance.

Any child that uses a Context needs to be nested inside the ContextProvider component. Every time the ContextProvider state changes it will render, and all its (non-memoized) children will render too.

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.