Home > Blockchain >  How to assign new array in useState variable
How to assign new array in useState variable

Time:12-15

My code is given below:

App.js

const [routes, setRoutes] = useState([]);
  const location = useLocation();
  const pathnames = location.pathname.split("/");
  const newNames = pathnames.map((name) =>
    name.replace("-", " ").toLocaleUpperCase()
  );
  const BreadCrumbs = newNames.filter((name) => name !== "");
  useEffect(() => {
    const createRoute = () => {
      setRoutes(BreadCrumbs);
    };
    createRoute();
  }, [BreadCrumbs]);

When the path is "home/all-activities/blogs", then routes=["HOME", "ALL ACTIVITIES", "BLOGS" ] The problem is app.js is rendering infinite times despite updating the state only once with useEffect hook. How can I resolve this?

CodePudding user response:

TL:DR Use useMemo. It will stop the infinite renders.

The problem is you are changing state with setRoutes, causing the component to re-render. When it re-renders, const BreadCrumbs is assigned a new value. This triggers useEffect again, and the whole thing starts over again, an infinite amount of times.

Try using useMemo on const BreadCrumbs.

Example:

const BreadCrumbs = useMemo(() => {
  return *some array*
}, [*dependencies go here*])

CodePudding user response:

There is no so much informations, so check this :

  1. Does your app contain a BrowserRouter ? https://reactrouter.com/en/main/router-components/browser-router

  2. Your dependencies array is wrong. The source of truth is "pathnames"

  3. maybe you can initialize the "route" state in a useEffect callback, you probably don't need a useEffect like this const [counter, setCounter] = useState(() => Math.floor(Math.random() * 16));

  • Related