Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

what are the reasons against using a setTimeout loop in the root component as the only way to call setState and cause rerenders

what are the reasons against using a loop like this in the root component

render() {
    setTimeout(() => {
            this.setState(({clock : true}))
        },17)
.
.
.
.
}

and then only changing state with regular assignments like

this.state.foo = bar

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One reason is that this approach requires constant re-rendering of every (non-memoized) component. On large pages, that could eat up a lot of the client’s processing power. Re-rendering will require each child to run its render method again, as well as componentDidUpdate. In functional components, the whole component function will run again. If any of your components have any non-trivial processing to do when rendering, that would pose a problem.

Another reason is that it results in very confusing looking code. React developers know not to mutate state directly. Coming across a codebase full of direct mutations would be exceedingly strange to parse when everything looks like a bug.

It’s trivial to change state properly with this.setState({ foo: bar }) – better to do it the proper way.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading