Home > Net >  UseEffect vs manual call function
UseEffect vs manual call function

Time:07-29

Recently I optimalized my code and I found out that in some cases I use useEffect and sometimes use other way to get the same result. Which makes me questions about best practice.

For example imagine 2 Selects, where the second one is dependent on the first one, more specifically the second one make api call whose result depends on the value from first Select.

...
const [ foodValue, setFoodValue ] = useState(null)
const { specificFoods } = useSelector(state => state.specificFoods)

const getSpecificFoodsOptions = () => (specificFoods.map(food => ({
    label: food.name,
    value: food.id
})))

const apiCall = () => {
    apiCallGetSpecificFoods(foodValue)
}

useEffect(() => {
    apiCallGetSpecificFoods(foodValue)
}, [foodValue])

return(
<>
    <Select
        name="food"
        options={[
            {
                label: "Vegetables",
                value: "vegetables"
            },
            {
                label: "Fruits",
                value: "fruits"
            }
        ]}
        value={foodValue}
        setValue = {setFoodValue}
        sideEffect={apiCall} // is better call apiCall manually or by useEffect ?
    />

    // Is better to create a condition based on data in state (in init state it's specificFood: null). 
    // I don't want show this Select, if the first one isn't selected.
    {
        specificFood &&
        <Select
            name="specific_food"
            options={apiCallGetSpecificFoods}
            value={specificFoodValue}
        />
    }
    
    // or this way ->
    {
        foodValue &&
        <Select
            name="specific_food"
            options={apiCallGetSpecificFoods}
            value={specificFoodValue}
        />
    }
</>
)

Or is it useless to deal with this?

CodePudding user response:

For example imagine 2 Selects, where the second one is dependent on the first one, more specifically the second one make api call whose result depends on the value from first Select.

I wouldn't use any useEffect for this, it is all triggered by user interaction. Put a change handler on the selects and call the API that way. You can memoize the change handler via useCallback if you want to optimize that.

  • Related