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.

react-tables-example

1. useEffect

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

select.tsx
useEffect(() => {
  // if there is no country selected
  if (!selectedCountry) {
    // just reset the state options
    return setStates([])
  }
 
  // fetch available states
  fetchStatesByCountry(selectedCountry)
}, [selectedCountry])

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

select.tsx
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>
)
0 view