andrerpena andrerpena - 1 year ago 153
Javascript Question

ReactJs: How to pass the initial state while rendering a component?

I know I can pass

while rendering a component. I'm also aware of the
method. But the problem is,
isn't quite helping because my component doesn't know it's initial state. I do. So I want to pass it while I'm rendering it.

Something like this (pseudo-code):

React.render(<Component initialState={...} />);

I know I could use a
to work as the initial state but this smells like an anti-pattern.

What should I do?


Imagine I have a
component. By the time I first render it, the initial state corresponds to the snapshot of current comments from my database. As the user includes comments, this list will change, and that's why it should be a
and not
. Now, in order to render the initial snapshot of comments I should pass it to the
component, because it has no way to know it. My confusion is that the only way I see to pass this information is through a
which seems to be an anti-pattern.

Answer Source

Only permanent components might be able to use props in the getInitialState. Props in getInitialState is an anti-pattern. getInitialState is only called when the component is first created so it may raise some bugs.

You can still do:

getInitialState: function() {
   return {foo:}

As they will be the default props for your app. But as long as you are using a prop to set a value that presumably won't change, you can use the same prop inside of the render function.


This props won't be modified, so no problem using it each time the render is called.

Edited answer:

In this case your initial state should not be a prop, should be an ajax call which populates the comment list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download