I'm reading a lot that of posts on here that recommend against using deeply nested state objects in React.
However, do these downsides apply to a state of a single-level object? Is there any performance difference between these two examples?
Will the first example cause rerenders just as much as the second? Does it even matter at such a small scale like this?
const [example, setExample] = useState({
group1property1: '',
group1property2: '',
group2property1: '',
group2property2: '',
});
const [example2, setExample2] = useState({
group1: {
property1: '',
property2: '',
},
group2: {
property1: '',
property2: '',
}
});
Is there any performance difference between these two examples?
No. When the state atom is reassigned (and you should already know you must not just internally modify an object/array state atom), the component is updated.
// not good; will not cause update since identity of `example` doesn't change
example.group1property1 = 8;
setExample(example);
// good; example is shallow-copied and updated
setExample(example => ({...example, group1property1: 8}));
Will the first example cause rerenders just as much as the second?
Yes, since you will need to shallow-copy the outer state atom to have React pick up changes in an inner object anyway. It's just that the updating of a deep object gets a bit tedious unless you use something like immer.
// not good; will not cause update, etc. etc.
example.group1.property1 = 8;
setExample(example);
// good; example is shallow-copied, as is group1
setExample(example => ({...example, group1: {...example.group1, ...property1: 8}}));
Does it even matter at such a small scale like this?
Probably not.