score:0
you can remove the wishlist variable from the dependency array.
when you call setwishlist
, it'll update the state, the dependency array will check that it has changed and will call the useeffect once more, thus the infinite cycle.
with an empty dependency array, it'll only run when your component mounts, fetching the data from your local storage and initializing your app. from there on, all you need is to handle the state locally and updating the localstorage with any new wishlist items, but that useeffect seems to be for initialization only.
update #1
the core issue here was that op was using localstorage to transfer data between components, which is not the correct way of doing things. if you happen to stumble upon op's problem and you're doing that, make sure to study a little bit about sharing data between components. the most common ways are context api, redux and passing data down as props.
you can read more about context here.
score:0
here you have add wishlist in dependency array of useeffect and in that you have added condition if (wishliststorage.length > 0) { setwishlist(wishliststorage); }
, because setting again the wishlist it will cause re-render and again useeffect will be triggered.
score:0
if i understand correctly, and you need this only for the initial render, then you can simply remove wishlist
from the dependency array.
const [wishlist, setwishlist] = react.usestate([]);
react.useeffect(() => {
if (typeof window !== "undefined") {
const wishliststorage =
localstorage.getitem("wishlist") === null
? []
: [...json.parse(localstorage.getitem("wishlist"))];
if (wishliststorage.length > 0) {
setwishlist(wishliststorage);
}
}
}, []);
score:0
you use wishlist
as the deps of useeffect
hooks, when the wishlist
cache exists, wishliststorage
is an object parsed from the local storage json string. then, you call setwishlist(wishliststorage)
, cause the hook re-render, the wishlist
will have a new reference. the useeffect
will execute again when its dependencies changes. that's why re-render infinitely.
you could use lazy initial state
the
initialstate
argument is the state used during the initial render. in subsequent renders, it is disregarded. if the initial state is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render
use the cache from the local storage to initial your state if it exists, otherwise, returns a default value.
e.g:
const [wishlist, setwishlist] = react.usestate(() => {
if (typeof window !== "undefined") {
const wishliststorage =
localstorage.getitem("wishlist") === null
? []
: [...json.parse(localstorage.getitem("wishlist"))];
return wishliststorage;
}
return [];
);
score:0
you are using setwishlist in useeffect that's observe wishlist, that's why it's lead you to infinity loop cuz when wishlist value changed it will execute the code in useeffect again and again so for my solution i saw localstorage in useeffect i would think it's would be only checked in first render, so you can simply remove [wishlist] -> []
const [wishlist, setwishlist] = react.usestate([]);
react.useeffect(() => {
if (typeof window !== "undefined") {
const wishliststorage =
localstorage.getitem("wishlist") === null
? []
: [...json.parse(localstorage.getitem("wishlist"))];
if (wishliststorage.length > 0) {
setwishlist(wishliststorage);
}
}
}, []);
score:1
just remove the wishlist from the dependencies
react.useeffect(() => {
if (typeof window !== "undefined") {
const wishliststorage =
localstorage.getitem("wishlist") === null
? []
: [...json.parse(localstorage.getitem("wishlist"))];
if (wishliststorage.length > 0) {
setwishlist(wishliststorage);
}
}
}, []);
Source: stackoverflow.com
Related Query
- useEffect causing component to re-render infinitely
- Filtering Table data with useEffect Hook causing component to re-render infinitely
- How to use useEffect hook properly with array dependency. I passed state from redux store and still my component renders infinitely
- React hook useEffect causes initial render every time a component mounts
- How to render a loading component with the useEffect hook?
- higher order function render twice causing child component to be triggered
- Why does useEffect hook with its dependencies run after first component render
- Using getDerivedStateFromProps to fetch API data is causing the component to render many times
- Why is set state in my useEffect causing the component to mount?
- React navbar component causing render to fail
- React 18 strict mode causing component to render twice
- React useEffect warning: Can't perform a React state update on an unmounted component causes switch statement to render wrong component
- How to update my UseEffect component to render new UI after a successful user login
- Why does my component render twice when using React's Context API and the useEffect hook?
- useEffect causing an infinite render loop
- Is React Router causing my component to render twice?
- Next.js render video only on desktop: useEffect can't perform a React state update on an unmounted component
- Component didn't render when I setState in useEffect
- How to avoid setState in useEffect hook causing second render
- Render HTML string as real HTML in a React component
- Make React useEffect hook not run on initial render
- React useEffect causing: Can't perform a React state update on an unmounted component
- Functions are not valid as a React child. This may happen if you return a Component instead of from render
- react router difference between component and render
- Jest Enzyme test a React component that returns null in render method
- React component render is called multiple times when pushing new URL
- Component won't render within NavigatorIOS - React Native
- React component children detect if empty / null before render
- React.js How to render component inside component?
- React, how to access the DOM element in my render function from the same component
More Query from same tag
- access clicking edit icon in material table
- Linking to different pages with the react-bootstrap navbar given error: Uncaught TypeError: router.createHref is not a function
- The right way to change a <select> value in a stateful React component
- React - change state when props are changed
- How do i loop through this in react
- How to use this.executeAction("someAction") in function based Component?
- React Jest to match snapshot, crash when testing component with child components
- Map an array of objects in react
- Serving REACT component using express is not working (just html file is rendered)
- child-parent components react (sharing)
- Loop buttons in react.js
- Can't perform a React state update on an unmounted component (useEffect react hooks)
- TypeError: Cannot read properties of undefined - React Redux Toolkit Testing
- [React Select]: Move the 'create-option' to the top
- useEffect running on every render even when dependency is unchanged
- The component styled.p with the id of "sc-iseJRi" has been created dynamically
- React Dynamic Table not showing in Knowckout project
- How to mock fetch when testing a React app?
- Please make sure the Element you are attempting to use is still mounted
- How to test a handle function call with a react functional component with hooks
- Is componentDidUpdate for the parent called when a child components state changes?
- How can I access this json response object?
- React-table in Material UI Dialog causes "Error: Maximum update depth exceeded. " when selecting a row and exporting it via useMountedLayoutEffect
- My array is not empty but array.length returns 0
- Fetch request in React: How do I Map through JSON array of objects, setState() & append?
- react-pdf loads file from disk but not url
- React email validation error not displaying
- Material UI Carousel autoplay and loading image issue
- filtering out users in react
- React Bootstrap dropdown menu styling problem