I am a C++ developer and new to React and JS. I somehow understand the concept of React and the reason it requires to have an immutable state:
- because it has to compare existing state on
setVar
(formuseState
) with a new state. Otherwise it will have no reason to rerender. - Because of the possible data races on shared resources (this is a problem in general in asynchronous programming, not just with React).
I also know, that there are common practices (looking throughout the history of React, I'd say they are still evolving) you have to stick to in order to work with other people in order to understand each other. But still, I really don't like the concept of copying data just for the sake of updating it:
- it feels like a lot of overhead for copying large arrays of data
- you have to come up with a rather complicated code to modify at least one element in an array. With trees it is even harder.
So, given the following assumptions, I want to ask if it might be alright to use a workaround to modify data in place:
- the data is not shared between other react components
- only one function is allowed to modify it
- the component will not read the data while it is being modified
These are just assumptions and maybe it is not possible to enforce in a real world application.
const Counter = () => {
const [clicks, setClicks] = useState({value: 0});
const [, setUpdateRequired] = useState({});
const increment = () => {
clicks.value -= 1;
// setClicks({value: clicks.value - 1}); // this is a proper way
setUpdateRequired({});
}
return (
<div>
<p>
Hi, my name is {name}.
You have clicked {clicks.value} times.
</p>
<p>
<button style={{
backgroundColor: 'gray',
border: '1px solid black'
}} onClick={increment}>Click Me!
</button>
</p>
</div>
)
}
Is this really that bad?
I expected the question to be downvoted. But:
I was looking for an explanation to thoroughly understand what could go wrong with this approach. I didn't find a question with regard to the subject as I put it:
Usually people ask why their components does not rerender when they modify state. The answer is - you must set state via a hook
. Fair point.
In my case I am confused: the hook I use to rerender component does not modify the counter value. It modifies a dummy object.
I thought that react could evaluate what needs to be updated and only partly rerender the component. But in that case I would not see an incremented counter each time I press a button.
I did mention in a question that it is most probably a very bad approach, but I fail to see the reason, so I would like to receive an explanation with examples.
This is not about asking for an opinion if it is bad. I ask WHY is it bad.