DEV Community

Cover image for 2 simple ways to call an action on state change
Marcos RJJunior
Marcos RJJunior

Posted on

2 simple ways to call an action on state change

Scenario

I would like to refresh the list of available states based on the selected country.

Example

1. useEffect

One of the parameters of this function is the array of values that works as a listener.

useEffect(() => {
  // if there is no country selected
  if (!selectedCountry) {
    // just reset the state options
    return setStates([])
  }

  // fetch available states
  fetchStatesByCountry(selectedCountry)
}, [selectedCountry])
Enter fullscreen mode Exit fullscreen mode

The useEffect will be performed only on the first render and when the value of selectedCountry changes.

It is a great place for this scenario, you have just to be careful to not using it much and lost control of the requests. Checking the network tab is a great place to see if you are not calling a request multiple times.

2. Simply calling a function

I feel comfortable using this simple approach because I know exactly who is triggering the action

const onCountryChange = e => {
  const selectedCountry = event.target.value

  // if there is no country selected
  if (!selectedCountry) {
    // just reset the state options
    return setStates([])
  }

  // fetch available states
  fetchStatesByCountry(selectedCountry)
}

return (
  <select onChange={onCountryChange}>
    <option value="AU">Australia</option>
    <option value="...">...</option>
  </select>
)
Enter fullscreen mode Exit fullscreen mode

Which one do you prefer?

Top comments (0)