What's the best solution for re-rendering child components on props change in React?












0















I have a parent component that fetches data in componentDidMount() hook. The state is setState()-d with this data. Then I pass the data to the child components as props and set their state based on these props. On the first render the props will be undefined because componentDidMount() hasn't executed yet. So, the child components get undefined props and the state is created with them. When the data fetches in componentDidMount() new props are passed to the child components, but the state is already created with undefined props and nothing changes. So, I am aware of two solutions now:





  • Use componentWillRecieveProps(). But this is now deprecated.


  • Use stateless child components. Pass the data to them as props from
    the parent component and don't set a state(use the data from props),
    and when the parent does a setState() in componentDidMount(), this
    will cause a re-render to child components with new props and
    everything works.





Now, what if I want to have stateful child components? I can't use the second method, and the first one is deprecated. What is the best solution to accomplish this?










share|improve this question


















  • 1





    I'd suggest another approach. Parent component's data should passed and handled as props only. Don't place passed props to child component's state. The latter should only contain data specific to this component. In this case you'll have no the above problem.

    – hindmost
    Nov 14 '18 at 13:06


















0















I have a parent component that fetches data in componentDidMount() hook. The state is setState()-d with this data. Then I pass the data to the child components as props and set their state based on these props. On the first render the props will be undefined because componentDidMount() hasn't executed yet. So, the child components get undefined props and the state is created with them. When the data fetches in componentDidMount() new props are passed to the child components, but the state is already created with undefined props and nothing changes. So, I am aware of two solutions now:





  • Use componentWillRecieveProps(). But this is now deprecated.


  • Use stateless child components. Pass the data to them as props from
    the parent component and don't set a state(use the data from props),
    and when the parent does a setState() in componentDidMount(), this
    will cause a re-render to child components with new props and
    everything works.





Now, what if I want to have stateful child components? I can't use the second method, and the first one is deprecated. What is the best solution to accomplish this?










share|improve this question


















  • 1





    I'd suggest another approach. Parent component's data should passed and handled as props only. Don't place passed props to child component's state. The latter should only contain data specific to this component. In this case you'll have no the above problem.

    – hindmost
    Nov 14 '18 at 13:06
















0












0








0








I have a parent component that fetches data in componentDidMount() hook. The state is setState()-d with this data. Then I pass the data to the child components as props and set their state based on these props. On the first render the props will be undefined because componentDidMount() hasn't executed yet. So, the child components get undefined props and the state is created with them. When the data fetches in componentDidMount() new props are passed to the child components, but the state is already created with undefined props and nothing changes. So, I am aware of two solutions now:





  • Use componentWillRecieveProps(). But this is now deprecated.


  • Use stateless child components. Pass the data to them as props from
    the parent component and don't set a state(use the data from props),
    and when the parent does a setState() in componentDidMount(), this
    will cause a re-render to child components with new props and
    everything works.





Now, what if I want to have stateful child components? I can't use the second method, and the first one is deprecated. What is the best solution to accomplish this?










share|improve this question














I have a parent component that fetches data in componentDidMount() hook. The state is setState()-d with this data. Then I pass the data to the child components as props and set their state based on these props. On the first render the props will be undefined because componentDidMount() hasn't executed yet. So, the child components get undefined props and the state is created with them. When the data fetches in componentDidMount() new props are passed to the child components, but the state is already created with undefined props and nothing changes. So, I am aware of two solutions now:





  • Use componentWillRecieveProps(). But this is now deprecated.


  • Use stateless child components. Pass the data to them as props from
    the parent component and don't set a state(use the data from props),
    and when the parent does a setState() in componentDidMount(), this
    will cause a re-render to child components with new props and
    everything works.





Now, what if I want to have stateful child components? I can't use the second method, and the first one is deprecated. What is the best solution to accomplish this?







javascript reactjs






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 12:51









LearningMathLearningMath

373220




373220








  • 1





    I'd suggest another approach. Parent component's data should passed and handled as props only. Don't place passed props to child component's state. The latter should only contain data specific to this component. In this case you'll have no the above problem.

    – hindmost
    Nov 14 '18 at 13:06
















  • 1





    I'd suggest another approach. Parent component's data should passed and handled as props only. Don't place passed props to child component's state. The latter should only contain data specific to this component. In this case you'll have no the above problem.

    – hindmost
    Nov 14 '18 at 13:06










1




1





I'd suggest another approach. Parent component's data should passed and handled as props only. Don't place passed props to child component's state. The latter should only contain data specific to this component. In this case you'll have no the above problem.

– hindmost
Nov 14 '18 at 13:06







I'd suggest another approach. Parent component's data should passed and handled as props only. Don't place passed props to child component's state. The latter should only contain data specific to this component. In this case you'll have no the above problem.

– hindmost
Nov 14 '18 at 13:06














3 Answers
3






active

oldest

votes


















1














static getDerivedStateFromProps(props, state)


is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
This method exists for rare use cases where the state depends on changes in props over time.



  static getDerivedStateFromProps(nextProps, prevState){
if(nextProps.someValue!==prevState.someValue){
return { someState: nextProps.someValue};
}
else return null;
}


For more details enter link description here






share|improve this answer



















  • 1





    But, read reactjs.org/blog/2018/06/07/…, before using this.

    – Sim Dim
    Nov 14 '18 at 13:22



















1














You can read this blog post.
In short a better approach would be to use fully uncontrolled component with key.




  1. Add a key to the child component based on data. If the data changes, the key changes and child component will re-mount.

  2. Provide data as props to the child, use this props as default state of child component.


Here is a sandbox example






share|improve this answer

































    0














    Consider using the replacement for componentDidReceiveProps, getDerivedStateFromProps, if you have state within a component which is informed by the values of the props it receives.



    https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops






    share|improve this answer























      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%2f53300683%2fwhats-the-best-solution-for-re-rendering-child-components-on-props-change-in-re%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














      static getDerivedStateFromProps(props, state)


      is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
      This method exists for rare use cases where the state depends on changes in props over time.



        static getDerivedStateFromProps(nextProps, prevState){
      if(nextProps.someValue!==prevState.someValue){
      return { someState: nextProps.someValue};
      }
      else return null;
      }


      For more details enter link description here






      share|improve this answer



















      • 1





        But, read reactjs.org/blog/2018/06/07/…, before using this.

        – Sim Dim
        Nov 14 '18 at 13:22
















      1














      static getDerivedStateFromProps(props, state)


      is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
      This method exists for rare use cases where the state depends on changes in props over time.



        static getDerivedStateFromProps(nextProps, prevState){
      if(nextProps.someValue!==prevState.someValue){
      return { someState: nextProps.someValue};
      }
      else return null;
      }


      For more details enter link description here






      share|improve this answer



















      • 1





        But, read reactjs.org/blog/2018/06/07/…, before using this.

        – Sim Dim
        Nov 14 '18 at 13:22














      1












      1








      1







      static getDerivedStateFromProps(props, state)


      is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
      This method exists for rare use cases where the state depends on changes in props over time.



        static getDerivedStateFromProps(nextProps, prevState){
      if(nextProps.someValue!==prevState.someValue){
      return { someState: nextProps.someValue};
      }
      else return null;
      }


      For more details enter link description here






      share|improve this answer













      static getDerivedStateFromProps(props, state)


      is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
      This method exists for rare use cases where the state depends on changes in props over time.



        static getDerivedStateFromProps(nextProps, prevState){
      if(nextProps.someValue!==prevState.someValue){
      return { someState: nextProps.someValue};
      }
      else return null;
      }


      For more details enter link description here







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 14 '18 at 13:08









      Jaisa RamJaisa Ram

      23137




      23137








      • 1





        But, read reactjs.org/blog/2018/06/07/…, before using this.

        – Sim Dim
        Nov 14 '18 at 13:22














      • 1





        But, read reactjs.org/blog/2018/06/07/…, before using this.

        – Sim Dim
        Nov 14 '18 at 13:22








      1




      1





      But, read reactjs.org/blog/2018/06/07/…, before using this.

      – Sim Dim
      Nov 14 '18 at 13:22





      But, read reactjs.org/blog/2018/06/07/…, before using this.

      – Sim Dim
      Nov 14 '18 at 13:22













      1














      You can read this blog post.
      In short a better approach would be to use fully uncontrolled component with key.




      1. Add a key to the child component based on data. If the data changes, the key changes and child component will re-mount.

      2. Provide data as props to the child, use this props as default state of child component.


      Here is a sandbox example






      share|improve this answer






























        1














        You can read this blog post.
        In short a better approach would be to use fully uncontrolled component with key.




        1. Add a key to the child component based on data. If the data changes, the key changes and child component will re-mount.

        2. Provide data as props to the child, use this props as default state of child component.


        Here is a sandbox example






        share|improve this answer




























          1












          1








          1







          You can read this blog post.
          In short a better approach would be to use fully uncontrolled component with key.




          1. Add a key to the child component based on data. If the data changes, the key changes and child component will re-mount.

          2. Provide data as props to the child, use this props as default state of child component.


          Here is a sandbox example






          share|improve this answer















          You can read this blog post.
          In short a better approach would be to use fully uncontrolled component with key.




          1. Add a key to the child component based on data. If the data changes, the key changes and child component will re-mount.

          2. Provide data as props to the child, use this props as default state of child component.


          Here is a sandbox example







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 14 '18 at 13:19

























          answered Nov 14 '18 at 13:00









          Sim DimSim Dim

          36527




          36527























              0














              Consider using the replacement for componentDidReceiveProps, getDerivedStateFromProps, if you have state within a component which is informed by the values of the props it receives.



              https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops






              share|improve this answer




























                0














                Consider using the replacement for componentDidReceiveProps, getDerivedStateFromProps, if you have state within a component which is informed by the values of the props it receives.



                https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops






                share|improve this answer


























                  0












                  0








                  0







                  Consider using the replacement for componentDidReceiveProps, getDerivedStateFromProps, if you have state within a component which is informed by the values of the props it receives.



                  https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops






                  share|improve this answer













                  Consider using the replacement for componentDidReceiveProps, getDerivedStateFromProps, if you have state within a component which is informed by the values of the props it receives.



                  https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 14 '18 at 13:04









                  Ben R.Ben R.

                  503210




                  503210






























                      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%2f53300683%2fwhats-the-best-solution-for-re-rendering-child-components-on-props-change-in-re%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

                      Bressuire

                      Vorschmack

                      Quarantine