Site currently work in progress

What Is Derived State?

In essence you shouldn’t store pieces of state for two of the same pieces of data.

Let’s take having a list of places as an example.

const [places, setPlaces] = useState([
    {id: 1, title: 'Some place'},
    {id: 2, title: 'Some other place'},
])

If we wanted to store the a selected place you might do something like this.

const [selectedPlace, setSelectedPlace] = useState()

You’re not storing the same information in two difference locations. If you were to now update the original state it wouldn’t update the select place. So for example our title changes to ‘New place’ our selectedPlace would still have ‘Some place’ as the title.

You want to derive state in this instance.

const [selectedPlaceId, setSelectedPlaceId] = useState()

const selectedPlace = places.find(place=> place.id === selectedPlaceId)

function selectPlace(id) {
    setSelectedPlaceId(id)
}

You may run in to performance issues so wrapping this within useMemo will save you a lot of headaches.

const selectedPlace = useMemo(() => {
  return places.find(place=> place.id === selectedPlaceId)
}, [places, selectedPlaceId])

Now this will only run is places or selectedPlaceId is updated.