What is the best approach to work with nested object in this.state?How to update nested state properties in ReactWhat is the most efficient way to deep clone an object in JavaScript?What is the best way to add options to a select from as a JS object with jQuery?What's the best way to break from nested (for) loops?Test for existence of nested JavaScript object keyWhat is the best way to detect a mobile device in jQuery?What is the best way to initialize a JavaScript Date to midnight?Access / process (nested) objects, arrays or JSONUsage of mutable objects inside React Native + Redux appHow to correctly handle data object from REST API using fetch in ReactUnexpected outcome with merging react state

What does "Puller Prush Person" mean?

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

Can I ask the recruiters in my resume to put the reason why I am rejected?

Do I have a twin with permutated remainders?

Replacing matching entries in one column of a file by another column from a different file

Malformed Address '10.10.21.08/24', must be X.X.X.X/NN or

Is it unprofessional to ask if a job posting on GlassDoor is real?

Which country benefited the most from UN Security Council vetoes?

Convert two switches to a dual stack, and add outlet - possible here?

What does it mean to describe someone as a butt steak?

Roll the carpet

Has there ever been an airliner design involving reducing generator load by installing solar panels?

What is a clear way to write a bar that has an extra beat?

Important Resources for Dark Age Civilizations?

Arrow those variables!

Why is consensus so controversial in Britain?

Approximately how much travel time was saved by the opening of the Suez Canal in 1869?

Languages that we cannot (dis)prove to be Context-Free

Why can't I see bouncing of a switch on an oscilloscope?

If human space travel is limited by the G force vulnerability, is there a way to counter G forces?

A case of the sniffles

Do infinite dimensional systems make sense?

NMaximize is not converging to a solution



What is the best approach to work with nested object in this.state?


How to update nested state properties in ReactWhat is the most efficient way to deep clone an object in JavaScript?What is the best way to add options to a select from as a JS object with jQuery?What's the best way to break from nested (for) loops?Test for existence of nested JavaScript object keyWhat is the best way to detect a mobile device in jQuery?What is the best way to initialize a JavaScript Date to midnight?Access / process (nested) objects, arrays or JSONUsage of mutable objects inside React Native + Redux appHow to correctly handle data object from REST API using fetch in ReactUnexpected outcome with merging react state






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I was reading the react documentation State Updates are Merged and theres a part it says when we set a object like this eg: this.setState(comments) it completely replaces this.state.comments.



So, I wonder if the approach to change name of user object on event onChangeText is valid, because the whole object it'll be replaced everytime onChangeText is called.



Is that a good practice or have side effects like bad perfomance?



example code:






this.state = 
user:
name: "",
surname: "",
,
isLoading: false
;
/***/
onChangeText=name => this.setState(
user:
...user,
name

)












share|improve this question
























  • take a look at: stackoverflow.com/a/51136076/5066625

    – Miroslav Glamuzina
    Mar 9 at 1:10

















2















I was reading the react documentation State Updates are Merged and theres a part it says when we set a object like this eg: this.setState(comments) it completely replaces this.state.comments.



So, I wonder if the approach to change name of user object on event onChangeText is valid, because the whole object it'll be replaced everytime onChangeText is called.



Is that a good practice or have side effects like bad perfomance?



example code:






this.state = 
user:
name: "",
surname: "",
,
isLoading: false
;
/***/
onChangeText=name => this.setState(
user:
...user,
name

)












share|improve this question
























  • take a look at: stackoverflow.com/a/51136076/5066625

    – Miroslav Glamuzina
    Mar 9 at 1:10













2












2








2


1






I was reading the react documentation State Updates are Merged and theres a part it says when we set a object like this eg: this.setState(comments) it completely replaces this.state.comments.



So, I wonder if the approach to change name of user object on event onChangeText is valid, because the whole object it'll be replaced everytime onChangeText is called.



Is that a good practice or have side effects like bad perfomance?



example code:






this.state = 
user:
name: "",
surname: "",
,
isLoading: false
;
/***/
onChangeText=name => this.setState(
user:
...user,
name

)












share|improve this question
















I was reading the react documentation State Updates are Merged and theres a part it says when we set a object like this eg: this.setState(comments) it completely replaces this.state.comments.



So, I wonder if the approach to change name of user object on event onChangeText is valid, because the whole object it'll be replaced everytime onChangeText is called.



Is that a good practice or have side effects like bad perfomance?



example code:






this.state = 
user:
name: "",
surname: "",
,
isLoading: false
;
/***/
onChangeText=name => this.setState(
user:
...user,
name

)








this.state = 
user:
name: "",
surname: "",
,
isLoading: false
;
/***/
onChangeText=name => this.setState(
user:
...user,
name

)





this.state = 
user:
name: "",
surname: "",
,
isLoading: false
;
/***/
onChangeText=name => this.setState(
user:
...user,
name

)






javascript reactjs react-native






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 11:34







Eduardo Breno

















asked Mar 9 at 1:02









Eduardo BrenoEduardo Breno

1135




1135












  • take a look at: stackoverflow.com/a/51136076/5066625

    – Miroslav Glamuzina
    Mar 9 at 1:10

















  • take a look at: stackoverflow.com/a/51136076/5066625

    – Miroslav Glamuzina
    Mar 9 at 1:10
















take a look at: stackoverflow.com/a/51136076/5066625

– Miroslav Glamuzina
Mar 9 at 1:10





take a look at: stackoverflow.com/a/51136076/5066625

– Miroslav Glamuzina
Mar 9 at 1:10












3 Answers
3






active

oldest

votes


















1














Inmutability is one point performance is another.



Inmutability meas that you should not use the same reference to update an object but to replace with a new one. In React this is recommended because plenty of updates only happen if the object is new. You could create a problem if you re-use the user in the state, change the name and then update the state with it. And that is why it is a recommendation, in most cases React magic will work on others it can't tell the difference. So you would have to



const copy = Object.assign(, this.state.user);


You can see this explanation here in the power of not mutating data



Performance in this case is concerning you because is a text listener, nevermind about it, React keeps track of the UI in a virtual DOM so it can update only what is different. This means everything will remain the same except for the new or deleted character.



You can try the clock example in the doc for that.






share|improve this answer






























    0














    I'd recommend set from lodash/fp:
    https://gist.github.com/jfmengels/6b973b69c491375117dc#_setpath-value-object






    share|improve this answer






























      0














      Your example is perfectly valid, provided the user variable is up-to-date.
      To ensure that, you might want to use the function arg form of setState. This will call your function with the current value of this.state and set state to the returned value.



      onChangeText=
      name =>
      this.setState(
      ( user ) => (
      user: ...user, name
      )
      )






      share|improve this answer























      • I understand, but i don't think is a good pratice replace whole object every time onChangeText is called.

        – Eduardo Breno
        Mar 9 at 11:37











      • you need to replace the top level object, or React won't detect the change and re-render. It's the premise of immutibility and change detection. With that code you swap the user object for a new object, but keep the same references for it's key values, except for name which you change.

        – lecstor
        Mar 9 at 11:41











      • actually, I'm thinking about PureComponent/Memo shallow prop checking. i think setState triggers re-render regardless. But if you pass those state values to child components that connect to Redux, or are PureComponents, or Memoed, then depending on where they are in the component props, mutating an object may mean re-renders don't always occur when they should.

        – lecstor
        Mar 9 at 11:44












      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55072981%2fwhat-is-the-best-approach-to-work-with-nested-object-in-this-state%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Inmutability is one point performance is another.



      Inmutability meas that you should not use the same reference to update an object but to replace with a new one. In React this is recommended because plenty of updates only happen if the object is new. You could create a problem if you re-use the user in the state, change the name and then update the state with it. And that is why it is a recommendation, in most cases React magic will work on others it can't tell the difference. So you would have to



      const copy = Object.assign(, this.state.user);


      You can see this explanation here in the power of not mutating data



      Performance in this case is concerning you because is a text listener, nevermind about it, React keeps track of the UI in a virtual DOM so it can update only what is different. This means everything will remain the same except for the new or deleted character.



      You can try the clock example in the doc for that.






      share|improve this answer



























        1














        Inmutability is one point performance is another.



        Inmutability meas that you should not use the same reference to update an object but to replace with a new one. In React this is recommended because plenty of updates only happen if the object is new. You could create a problem if you re-use the user in the state, change the name and then update the state with it. And that is why it is a recommendation, in most cases React magic will work on others it can't tell the difference. So you would have to



        const copy = Object.assign(, this.state.user);


        You can see this explanation here in the power of not mutating data



        Performance in this case is concerning you because is a text listener, nevermind about it, React keeps track of the UI in a virtual DOM so it can update only what is different. This means everything will remain the same except for the new or deleted character.



        You can try the clock example in the doc for that.






        share|improve this answer

























          1












          1








          1







          Inmutability is one point performance is another.



          Inmutability meas that you should not use the same reference to update an object but to replace with a new one. In React this is recommended because plenty of updates only happen if the object is new. You could create a problem if you re-use the user in the state, change the name and then update the state with it. And that is why it is a recommendation, in most cases React magic will work on others it can't tell the difference. So you would have to



          const copy = Object.assign(, this.state.user);


          You can see this explanation here in the power of not mutating data



          Performance in this case is concerning you because is a text listener, nevermind about it, React keeps track of the UI in a virtual DOM so it can update only what is different. This means everything will remain the same except for the new or deleted character.



          You can try the clock example in the doc for that.






          share|improve this answer













          Inmutability is one point performance is another.



          Inmutability meas that you should not use the same reference to update an object but to replace with a new one. In React this is recommended because plenty of updates only happen if the object is new. You could create a problem if you re-use the user in the state, change the name and then update the state with it. And that is why it is a recommendation, in most cases React magic will work on others it can't tell the difference. So you would have to



          const copy = Object.assign(, this.state.user);


          You can see this explanation here in the power of not mutating data



          Performance in this case is concerning you because is a text listener, nevermind about it, React keeps track of the UI in a virtual DOM so it can update only what is different. This means everything will remain the same except for the new or deleted character.



          You can try the clock example in the doc for that.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 9 at 1:12









          cutikocutiko

          3,11021934




          3,11021934























              0














              I'd recommend set from lodash/fp:
              https://gist.github.com/jfmengels/6b973b69c491375117dc#_setpath-value-object






              share|improve this answer



























                0














                I'd recommend set from lodash/fp:
                https://gist.github.com/jfmengels/6b973b69c491375117dc#_setpath-value-object






                share|improve this answer

























                  0












                  0








                  0







                  I'd recommend set from lodash/fp:
                  https://gist.github.com/jfmengels/6b973b69c491375117dc#_setpath-value-object






                  share|improve this answer













                  I'd recommend set from lodash/fp:
                  https://gist.github.com/jfmengels/6b973b69c491375117dc#_setpath-value-object







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 9 at 1:13









                  MarkusMarkus

                  1,21311230




                  1,21311230





















                      0














                      Your example is perfectly valid, provided the user variable is up-to-date.
                      To ensure that, you might want to use the function arg form of setState. This will call your function with the current value of this.state and set state to the returned value.



                      onChangeText=
                      name =>
                      this.setState(
                      ( user ) => (
                      user: ...user, name
                      )
                      )






                      share|improve this answer























                      • I understand, but i don't think is a good pratice replace whole object every time onChangeText is called.

                        – Eduardo Breno
                        Mar 9 at 11:37











                      • you need to replace the top level object, or React won't detect the change and re-render. It's the premise of immutibility and change detection. With that code you swap the user object for a new object, but keep the same references for it's key values, except for name which you change.

                        – lecstor
                        Mar 9 at 11:41











                      • actually, I'm thinking about PureComponent/Memo shallow prop checking. i think setState triggers re-render regardless. But if you pass those state values to child components that connect to Redux, or are PureComponents, or Memoed, then depending on where they are in the component props, mutating an object may mean re-renders don't always occur when they should.

                        – lecstor
                        Mar 9 at 11:44
















                      0














                      Your example is perfectly valid, provided the user variable is up-to-date.
                      To ensure that, you might want to use the function arg form of setState. This will call your function with the current value of this.state and set state to the returned value.



                      onChangeText=
                      name =>
                      this.setState(
                      ( user ) => (
                      user: ...user, name
                      )
                      )






                      share|improve this answer























                      • I understand, but i don't think is a good pratice replace whole object every time onChangeText is called.

                        – Eduardo Breno
                        Mar 9 at 11:37











                      • you need to replace the top level object, or React won't detect the change and re-render. It's the premise of immutibility and change detection. With that code you swap the user object for a new object, but keep the same references for it's key values, except for name which you change.

                        – lecstor
                        Mar 9 at 11:41











                      • actually, I'm thinking about PureComponent/Memo shallow prop checking. i think setState triggers re-render regardless. But if you pass those state values to child components that connect to Redux, or are PureComponents, or Memoed, then depending on where they are in the component props, mutating an object may mean re-renders don't always occur when they should.

                        – lecstor
                        Mar 9 at 11:44














                      0












                      0








                      0







                      Your example is perfectly valid, provided the user variable is up-to-date.
                      To ensure that, you might want to use the function arg form of setState. This will call your function with the current value of this.state and set state to the returned value.



                      onChangeText=
                      name =>
                      this.setState(
                      ( user ) => (
                      user: ...user, name
                      )
                      )






                      share|improve this answer













                      Your example is perfectly valid, provided the user variable is up-to-date.
                      To ensure that, you might want to use the function arg form of setState. This will call your function with the current value of this.state and set state to the returned value.



                      onChangeText=
                      name =>
                      this.setState(
                      ( user ) => (
                      user: ...user, name
                      )
                      )







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 9 at 5:59









                      lecstorlecstor

                      4,0761318




                      4,0761318












                      • I understand, but i don't think is a good pratice replace whole object every time onChangeText is called.

                        – Eduardo Breno
                        Mar 9 at 11:37











                      • you need to replace the top level object, or React won't detect the change and re-render. It's the premise of immutibility and change detection. With that code you swap the user object for a new object, but keep the same references for it's key values, except for name which you change.

                        – lecstor
                        Mar 9 at 11:41











                      • actually, I'm thinking about PureComponent/Memo shallow prop checking. i think setState triggers re-render regardless. But if you pass those state values to child components that connect to Redux, or are PureComponents, or Memoed, then depending on where they are in the component props, mutating an object may mean re-renders don't always occur when they should.

                        – lecstor
                        Mar 9 at 11:44


















                      • I understand, but i don't think is a good pratice replace whole object every time onChangeText is called.

                        – Eduardo Breno
                        Mar 9 at 11:37











                      • you need to replace the top level object, or React won't detect the change and re-render. It's the premise of immutibility and change detection. With that code you swap the user object for a new object, but keep the same references for it's key values, except for name which you change.

                        – lecstor
                        Mar 9 at 11:41











                      • actually, I'm thinking about PureComponent/Memo shallow prop checking. i think setState triggers re-render regardless. But if you pass those state values to child components that connect to Redux, or are PureComponents, or Memoed, then depending on where they are in the component props, mutating an object may mean re-renders don't always occur when they should.

                        – lecstor
                        Mar 9 at 11:44

















                      I understand, but i don't think is a good pratice replace whole object every time onChangeText is called.

                      – Eduardo Breno
                      Mar 9 at 11:37





                      I understand, but i don't think is a good pratice replace whole object every time onChangeText is called.

                      – Eduardo Breno
                      Mar 9 at 11:37













                      you need to replace the top level object, or React won't detect the change and re-render. It's the premise of immutibility and change detection. With that code you swap the user object for a new object, but keep the same references for it's key values, except for name which you change.

                      – lecstor
                      Mar 9 at 11:41





                      you need to replace the top level object, or React won't detect the change and re-render. It's the premise of immutibility and change detection. With that code you swap the user object for a new object, but keep the same references for it's key values, except for name which you change.

                      – lecstor
                      Mar 9 at 11:41













                      actually, I'm thinking about PureComponent/Memo shallow prop checking. i think setState triggers re-render regardless. But if you pass those state values to child components that connect to Redux, or are PureComponents, or Memoed, then depending on where they are in the component props, mutating an object may mean re-renders don't always occur when they should.

                      – lecstor
                      Mar 9 at 11:44






                      actually, I'm thinking about PureComponent/Memo shallow prop checking. i think setState triggers re-render regardless. But if you pass those state values to child components that connect to Redux, or are PureComponents, or Memoed, then depending on where they are in the component props, mutating an object may mean re-renders don't always occur when they should.

                      – lecstor
                      Mar 9 at 11:44


















                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55072981%2fwhat-is-the-best-approach-to-work-with-nested-object-in-this-state%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                      Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                      How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page