Reputation: 99
Hello I am trying to use a UseEffect of react hooks, I know I can add variables that on change can activate it, but I would like to know if there is a way to activate the useEffect only when the value meets certain criteria.
I have already created a conditional inside the useEffect and I know it works, but I would like to know if there's another way to do it.
useEffect(() => {
doSomething();
if(!isOpen)
doSomething2();
}, [isOpen, otherThing]);
In the example above I want doSomething2 to work only when its value is false.
isOpen in this examample has a default value of false, then when it retrieves something from the database it turns into true and finally when it finished fetching it goes back to false.
I expect the hook to activate only when the value switches from true to false and not in every change.
Is there a way to do that?
Upvotes: 5
Views: 10825
Reputation: 3801
you can have multiple data that can be changed like this.
const [selectedCategory, setSelectedCategory] = React.useState(null);
const [restaurants, setRestaurants] = React.useState({});
if you want to get an event for a specific attribute like restaurants
then you can use one useEffect
method for that. and for the other one, you can use another useEffect
method like below.
const [selectedCategory, setSelectedCategory] = React.useState(null);
const [restaurants, setRestaurants] = React.useState(restaurantData);
useEffect(() => {
console.log("this is for selectedCategory")
}, [selectedCategory]);
useEffect(() => {
console.log("this is for restaurants")
}, [restaurants]);
Thanks.
Upvotes: 0
Reputation: 5786
No other way. Your attempt is already correct. That's the only way. Cheers!
useEffect()
only allows dependencies and no conditional attributes.
Upvotes: 4