I have an useEffect with 2 states in the dependancies array that is something like this:
const [currentTab, setCurrentTab] = useState('open');
const [searchParams, setSearchParams] = useState('');
useEffect(() => {
if (condition) {
// useEffect logic
} else {
return;
}, [currentTab, searchParams]);
But I want that this conditional be applied only if the trigger of the useEffect was the currentTab, else if the trigger was the searchParams I’d like to run this useEffect logic without any conditions. What is the best approach to solve this?
I’ve already tried splitting it in two different useEffects for each state in order to doing conditional in only one but didn’t worked either bc this way would run both useEffects when the component mounts and that’s not the expected.
2
Answers
You can try using
useRef
to keep previous currentTab valueBut I’m not sure there isn’t a way to make the component logic more straightforward. Perhaps there is a better way to organise the code. For example (no sure if you can apply it in your app), you can change the
key
prop of a component, which will cause the component to be re-rendered from scratch.You can achieve this by using a single
useEffect
hook with a conditional statement inside it. You can check which state has changed using theuseState
setter function’s previous value. Here’s an example:This way, you can apply the conditional logic only when the
currentTab
state changes and skip it when thesearchParams
state changes.Note:
useState[0]
anduseState[1]
are used to access the previous values ofcurrentTab
andsearchParams
respectively. This is a common pattern when working with multiple states in a singleuseEffect
hook.Also, make sure to add the necessary dependencies in the
useEffect
array to ensure it runs when the states change.