Cons of using React context

Tags:
Date:

Monday 08/08/2022

The biggest con when using React context is it may lead to performance issues.

It is rerendering all the components that under the context provider each time the context state changes.

For example:

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

export const CounterContext = React.createContext();

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <CounterContext.Provider value={{ count, setCount }}>
      <Counter />
      <DateText />
    </CounterContext.Provider>
  );
}

function Counter() {
  const { count, setCount } = useContext(CounterContext);
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>increment</button>
    </div>
  );
}

function DateText() {
  return <h1>{new Date().toString()}</h1>;
}

We have here two seperate components Counter and DateText.

They both are under the CounterContext so every time we will increment the counter, DateContext will rerender even if we don't consume state from the context.

© 2023 Vadim Alakhverdov