score:0
It's not suprising - when You adding the values list in the dependency array, the useEffect will execute on every change of the value list - that leads to the infinite loop :)
According to the previous answer of @norbitrial, hiding of the error will not resolve the things, becuase every dependency from scope MUST be declared in the dependencies array, avoiding it can lead to unexpected behaviours.
I would recommend to consider using useReducer
in this situation. It will cause that logic of modifications of the dependency array can be moved out of the useEffect
hooks' scope - and You will be not forced to attach it as a dependency of useEffect
.
score:1
Ideally, you would add some condition/check to see if values
already has the value that you want. As setValues
appears to be called on every render, which triggers a re-render, times infinity.
Potentially, using something like Lodash's isEqual combined with Lodash's orderBy would do this trick (because sort will mutate the original array).
const [ascValue, setAscValue] = useState(true);
const [values, setValues] = useState([
{ id: 10 },
{ id: 5 },
{ id: 12 },
{ id: 1 },
{ id: 2 },
{ id: 900 },
{ id: 602 }
]);
useEffect(() => {
function sortValues() {
const sorter = ascValue ? "asc" : "desc";
if (!_.isEqual(values, _.orderBy(values, ["id"], [sorter]))) {
console.log("logged");
setValues(() => _.orderBy(values, ["id"], [sorter]));
}
}
sortValues();
}, [ascValue, values]);
The point is, useEffect shouldn't set state every on every render by default (it can once render has finished and the user triggers an action).
A fork of your CodeSandbox to demonstrate that the side effect should only update the components state if the condition is met.
score:2
I don't see any issues with your code. What I would do is just simply ignore the warning by adding // eslint-disable-next-line react-hooks/exhaustive-deps
as the following:
useEffect(() => {
function sortValues() {
let sorted;
const array = [...values];
if (ascValue) {
sorted = array.sort((a, b) => a - b);
} else {
sorted = array.sort((a, b) => b - a);
}
setValues(sorted);
}
sortValues();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ascValue]);
Maybe one shortening on sortValues()
:
function sortValues() {
const compare = ascValue ? (a, b) => a - b : (a, b) => b - a;
setValues([...values].sort(compare));
}
I hope that helps!
Source: stackoverflow.com
Related Query
- useEffect is missing a dependency, but when I add it I get a 'maximum update depth exceeded' error
- How to fix missing dependency warning when using useEffect Hook to update state when props change
- How to fix missing dependency warning when using useEffect React Hook
- React and Socket.io: Able to get initial data - but view doesn't update when a new post comes in
- useEffect missing dependency when using redux useDispatch
- React Hook useEffect has a missing dependency when passing empty array as second argument
- React warning React Hook useEffect has a missing dependency when the deps are []
- React useEffect doesn't trigger sometimes when I update my list as its dependency
- How to include missing dependency in useEffect but prevent infinite loop execution of function?
- State from react useState is updated when key property is used but requires useEffect or similar method to update otherwise
- React useEffect warning to put missing dependency. But dependency value changes in the hook
- React hooks : useMemo and useEffect has a Missing dependency when we are trying to call a function
- window.visualViewport.height doenst update useEffect when a dependency
- React Hook useEffect has a missing dependency when updating state based on current value
- fix missing dependency warning when missing an object in useEffect React Hook?
- I get error Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate
- How to fix missing dependency warning when using useEffect React Hook? I am using nextjs app
- How to get useEffect to only update on changes when the change is from another component
- React Hook useEffect has a missing dependency when function call
- React useEffect Hook when only one of the effect's deps changes, but not the others
- What if I add multiple dependency in React's useEffect second parameter?
- ECONNREFUSED when making GET request in app, but API returns JSON successfully
- React Hook useEffect has missing dependencies. Either include them or remove the dependency array
- How to fix "React Hook useEffect has a missing dependency. Either include it or remove the dependency array" problem?
- Why is a state variable's setter needed as a dependency with useEffect when passed in through props?
- useEffect not working when dependency value changed
- React-hook-form field value get lost when i collapse, add or delete panel
- Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate
- Maximum update depth exceeded. Infinity loop when using TimePickerInput onChange event React.js
- React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array react-hooks/exhaustive-deps
More Query from same tag
- Errors with onSubmit handler if submit is called via this.props.submit('formname')
- Navigate to other page upon button click in react
- mapDispatchToProps is not putting my function into props
- Overriding with classes in material-ui v1.0.0-beta-1 shows "the key provided to the classes property is not implemented" warning
- Issues with geting results from filter inside filters
- React - Mapped array not passing props correctly to child component
- React - state property is undefined - Why?
- Why no parentheses on a function
- Set LI element to inactive state on clicking button in React JS
- Is there any way to set background-color by label in google chart?
- How render form on new page using React NavLink?
- Await API calls before render private route
- Is it possible to add a custom hover color to Raised Buttons?
- I want to create a custom radioButton with framer-motion
- updating multiple items in redux array
- Tailwind transition delay arbitrary value only working for specific values
- Pass down onChange to child component in react
- I cannot get image to render after a network query
- Reactjs how call data from database (and wait for it) in componentDidMount (onClick event)
- unable to clear flatpickr selected date on click of cross icon
- Trying to render 4 videos to my application from an api call to youtube
- How can I display nested component with React router?
- Error when compiling with webpack and babel-loader
- css every n-th img in new row
- cant add image in react getting an error Error: Cannot find module './undefined' when using require
- Spread Operator for array of array
- Passing React variable to "href" attribute
- React - Using componentDidUpdate to update state based on data passed from another function
- react component re rendered multiple times when trying to invoke itself?
- Linear-graident MUI theme background just goes white