Home > OS >  too many renders using useContext and createContext
too many renders using useContext and createContext

Time:09-06

facing a multiple rendering issue when using useContext, here are code examples and prints showing the multiple log on each click I'm new to using context and I'm trying to understand the concepts and whys of multi-rendering, one possibility would be to use useEffect to create something like 'didMount' or something like that, but I don't know where to put this code

Editor Page..

// react
import React, { useState, useEffect } from 'react';
// components
import Header from '../../components/header/Header';
import EditHands from './components/edit-hands/EditHands';
// context
import { EditorProvider } from '../../contexts/EditorContext';

const Editor = () => {
  return (
    <>
      <Header />
      <EditorProvider>
        <p>Editor</p>
        <EditHands />
      </EditorProvider>
    </>
  );
};

export default Editor;

Editor Context

import { createContext, useState } from 'react';

export const editorContext = createContext();

export const EditorProvider = ({ children }) => {
  //
  const [counter, setCounter] = useState(0);
  const increaseCounter = () => setCounter(counter   1);

  return (
    <editorContext.Provider value={{ counter, increaseCounter }}>
      {children}
    </editorContext.Provider>
  );
};

Edit Hands => Components using context and mult rendering

import React, { useContext } from 'react';
// database
import { hands } from '../../../../database/db';
// context
import { editorContext } from '../../../../contexts/EditorContext';

const EditHands = () => {
  const { counter, increaseCounter } = useContext(editorContext);

  console.log('Edit Hands counter value: ', counter);

  return (
    <>
      <button>{counter}</button>
      <button onClick={increaseCounter}>Increase</button>
      <div className='hands-containner'>
        {hands.map((hand, i) => (
          <span key={i}>{hand}</span>
        ))}
      </div>
    </>
  );
};
export default EditHands;

SS from console.log inside EditHands

enter image description here

CodePudding user response:

It seems Strict Mode of React is invoking the function component twice, so your code is fine as it is.

Strict Mode is only active in development mode for safe code writing. So when you run it in production mode or turn off the Strict Mode, the problem would be gone.

In React 17, console.log is silenced by the React. But Since version 18, React does not suppress any logs. Check the documentation about this, and other StackOverflow Question.

  • Related