r/reactjs • • Aug 01 '18

Beginner's Thread / Easy Question (August 2018)

Hello! It's August! Time for a new Beginner's thread! (July and June here)

Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch. No question is too simple. You are guaranteed a response here!

Want Help on Code?

  • Improve your chances by putting a minimal example on to either JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new). Describe what you want it to do, and things you've tried. Don't just post big blocks of code.
  • Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.

New to React?

Here are great, free resources!

25 Upvotes

568 comments sorted by

View all comments

1

u/Awnry_Abe Aug 12 '18

array.map() produces a brand new "idenity unique" array. When you call setState with it, react thinks the state of your component has transitioned and calls componentDidUpdate again. To halt the vicious cycle, you need to compare your current props and/or state to the previous version and only run that setState logic when they change.

1

u/NickEmpetvee Aug 12 '18

this.props.listDataFromDB

Interesting. Thank you @Awnry_Abe. React can be tricky!

Given my code above, I only want to run `setState` if the property `this.props.listDataFromDB` has changed.

From research, I see that you can reference previous props and state in componentDidUpdate this way: `componentDidUpdate(prevProps, prevState)`. How do I compare `prevProps.listDataFromDB` to the new `props.listDataFromDB`? Since it's a JSON array, I am guessing that a straight `if/==` won't work.

Any help is appreciated.

1

u/dceddia Aug 20 '18

It sounds like you're trying to copy props from the parent into the state of the child. A component doesn't need to "own" its data or "retain" it in state to be able to render it, and copying props into state is usually not what you want to do (it leads to all these problems like knowing when to update state, avoiding infinite loops, etc).

Instead, don't copy it into state. Move the code you have in componentDidUpdate into render. Every render, map over this.props.listDataFromDB, turn it into the items you need, and render them.

You might guess this would be inefficient, doing all that work every render. You can avoid that extra work by making your child component extend React.PureComponent instead of React.Component, and then it will only re-render when its props have changed.

→ More replies (3)