Problems with the State Hook

The State Hook already supports passing complex objects and arrays to it, and it can handle their state changes perfectly well. However, we are always going to have to change the state directly, which means that we need to use a lot of spread syntax, in order to make sure that we are not overwriting other parts of the state. For example, imagine that we have a state object like this:

const [ config, setConfig ] = useState({ filter: 'all', expandPosts: true })

Now, we want to change the filter:

setConfig({ filter: { byAuthor: 'Daniel Bugl', fromDate: '2019-04-29' } })

If we simply ran the preceding code, we would be removing the expandPosts part of our state! So, we need to do the following:

setConfig({ ...config, filter: { byAuthor: 'Daniel Bugl', fromDate: '2019-04-29' } })

Now, if we wanted to change the fromDate filter to a different date, we would need to use spread syntax twice, to avoid removing the byAuthor filter:

setConfig({ ...config, filter: { ...config.filter, fromDate: '2019-04-30' } })

But, what happens if we do this when the filter state is still a string? We are going to get the following result:

{ filter: { '0': 'a', '1': 'l', '2': 'l', fromDate: '2019-04-30' },
expandPosts: true }

What? Why are there suddenly three new keys—0, 1, and 2? This is because spread syntax also works on strings, which are spread in such a way that each letter gets a key, based on its index in the string.

As you can imagine, using spread syntax and changing the state object directly can become very tedious for larger state objects. Furthermore, we always need to make sure that we do not introduce any bugs, and we need to check for bugs in multiple places all across our app.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.193.158