Home > Back-end >  what are the reasons against using a setTimeout loop in the root component as the only way to call s
what are the reasons against using a setTimeout loop in the root component as the only way to call s

Time:07-10

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

CodePudding user response:

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.

  • Related