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

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme