I run into this more and more frequently in various forms: (simplified example)
const searchParameters = useState();
const sorting = useState();
// update searchParameters if the user enters someting
// update sorting if the user clicks on a column in the table
// PROBLEM: I only want to call loadEntries() if sorting changes, but I need searchParameters for it too!
useEffect(
() => loadEntries(sorting, searchParameters),
// eslint-disable-next-line react-hooks/exhaustive-deps
[sorting]
);
- Is there a way to deal with this situation without having to disable
react-hooks/exhaustive-deps?
- (less important) is there a way to disable
react-hooks/exhaustive-deps
for only a specific dependency? (searchParameters in this case)
2
Answers
You can use a
ref
to hold the current value ofsearchParameters
, and since theref
itself doesn’t change (only thecurrent
property) you don’t even need to state it as a dependency:As far as I know, you can’t disable
react-hooks/exhaustive-dep
for a specific property likesearchParameters
. The configuration only deals with the rules.The answer from @OriDrori would address the question.
The following is an alternate solution, not based on ref. Certainly it comes at a cost of an extra state and a separate useEffect statement.
Coding highlights
a. An extra state for sorting
b. Two separate useEffect invocations
The first useEffect will invoke for every render, but the logic inside will be applied with respect to the changes in sorting state.
The second useEffect will invoke only on the changes in sorting state, and will keep preSorting state in synch.
Code – full listing:
App.js
Test runs
A search parameter newly entered
It did not invoke useEffect for the changes in Sorting, please see there is nothing logged in the console
A change in Sorting by clicking the button
It did invoke useEffect for the changes in Sorting, please see there is something logged in the console.
A change in the search parameter
It did not invoke useEffect for changes in Sorting, please see there is nothing newly logged in the console.
A change in Sorting by clicking the button
It did invoke useEffect for changes in Sorting, please see there is something newly logged in the console.