In React app I have a code to toggle html element's (let's call it element A) class when pushing a button. I do it by mutating a state which contains settings for the whole app. Then when the element A is rendered it checks the appropriate setting and apply or not apply the class to it.
This works, but it takes a long time to re-render everything and thus there is a lag between click and changes applied. So I thought to use a little hack here with classic DOM manipulation to first change class (to see changes instantaneously) and then let React re-render everything.
The issue I have is that the changes are not applied by DOM manipulation, but only later after re-render. When I comment the setState line, the changes are visible immediately.
My question is, how to achieve instant class change and what could be wrong here?
const handleCollapseToggle = (i, el) => {
const helpToggler = document.getElementById(el);
helpToggler.classList.toggle('is-hidden');
console.log('test',helpToggler);
const newCollapsed = Array.from(settings.collapsed);
newCollapsed[i] = !newCollapsed[i];
const newSettings = {
...settings,
collapsed:newCollapsed
}
setSettings(newSettings);
//setTimeout(setSettings(newSettings), 10000);
}
I have also tried the setTimeout to apply a new state (please see on the last commented line of code), but that did not work and even did take less then 10 seconds to re-render. Also the console.log('test',helpToggler) logs out the 'test' word first and then the element itself later after re-render (on the same console log line).