Home > OS >  React context is not re-rendering after state change
React context is not re-rendering after state change

Time:10-20

So I have added react context api to my website but the website is not re-rendering after I change the state that is in the context

Here is my context file

    import { createContext, useEffect, useState } from "react";
import { item } from "../Types";

interface AppContextInterface {
  Addtofavorite: (item: item) => void;
  Addtocart: (item: item) => void;
  Items: item[];
  setItems: (item: item[]) => void;
  Favorite: item[];
  Cart: item[];
}

export const AppContext = createContext<AppContextInterface>(
  {} as AppContextInterface
);

export const AppContextProvider = ({ children }: any) => {
  const [favorite, addFavorite] = useState([] as item[]);
  const [cart, addCart] = useState([] as item[]);
  const [items, setItems] = useState([] as item[]);

  useEffect(() => {
    console.log("asdasd");
  }, [favorite, cart]);

  const handleAddFavorite = (item: item) => {
    addFavorite(AddElementToArray(item, favorite));
    console.log(favorite);
  };

  const handleAddCart = (item: item) => {
    addCart(AddElementToArray(item, cart));
    console.log(cart);
  };

  const AddElementToArray = (item: item, array: item[]) => {
    if (array.includes(item)) {
      array.splice(array.indexOf(item), 1);
    } else {
      array.push(item);
    }
    return array;
  };
  const values = {
    Addtofavorite: handleAddFavorite,
    Addtocart: handleAddCart,
    Items: items,
    setItems: setItems,
    Favorite: favorite,
    Cart: cart,
  };

  return <AppContext.Provider value={values}>{children} </AppContext.Provider>;
};

this is my index.tsx file

  import React from "react";
    import ReactDOM from "react-dom/client";
    import App from "./Components/App";
    import { AppContextProvider } from "./Context/AppContext";
    
    const root = ReactDOM.createRoot(
      document.getElementById("root") as HTMLElement
);
root.render(
  <React.StrictMode>
    <AppContextProvider>
      <App />
    </AppContextProvider>
  </React.StrictMode>
);

am I wrong about that react context should re-render itself and its children after state changing or is it that I did something wrong ?

CodePudding user response:

react will not update all child components when context will change. it only updates components where you use context by useContext hook

CodePudding user response:

React states need to be immutable. When you set state, react does a === between the old and new state. If you've been mutating the array, that comparison will return true, and react skips rendering because it thinks nothing has changed.

So instead of using push/splice on the existing array, create a new one instead.

const AddElementToArray = (item: item, array: item[]) => {
  if (array.includes(item)) {
    return array.filter(original => item !== original);
  } else {
    return [...array, item];
  }
}
  • Related