Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Basics (retired) Component Lifecycle Component Lifecycle Review

Possible problem with quiz question: changing state in render() method

Hi,

It seems to me the following question is graded incorrectly. I don't recall specific discussion in the training videos that addresses this precise situation, but it seems to go against the idea of render USING the state to decide how and what to render. If render CHANGES the state, then we might end up with a complex series of re-renders, with the risk that these state-changing render calls may never terminate if our logic is faulty or badly designed.

Let me know if I'm missing something or wrong.

Thanks,

Jere

Quiz Question 1 of 5

It is acceptable to modify your state information in the render() method to make it acceptable for display.

My chosen answer: False

Response: Bummer! Unfortunately, that answer is incorrect.

SOURCES SUGGESTING THE ANSWER IS INCORRECT:

URL: https://facebook.github.io/react/docs/react-component.html#render

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser.

URL: https://github.com/facebook/react/issues/5591 title: Calling setState in render causes infinite loop #5591

- includes comments like:

jimfb commented on Dec 3, 2015

In general, this should never happen; you should not be doing anything remotely related to modifying any component's state within a render function.

I'm curious what your use case is, for having a callback which does a setState; mind sharing?

2 Answers

Seth Kroger
Seth Kroger
56,413 Points

The question is: "It is acceptable to modify your state information in the render() method to make it acceptable for display." The wording is a bit ambiguous but I don't think it's asking if it's acceptable to "modify state directly" (which would be a no-no). The key here is the last part "to make it acceptable for display" which implies "modify the information you get from state".

I see your point. I had interpreted the question as "modifying the state itself" in the render function rather than "creating display data derived from the state without changing the state itself".