React 16.7 has State Hook, can I use functional component instead of class component in any situation?











up vote
0
down vote

favorite
1












React 16.7 has State Hook,so I can use function component instead of class component in any situation,is it right?
https://reactjs.org/docs/hooks-state.html










share|improve this question




















  • 1




    Yep, everything you can do with class components you will be able to do with functional components + hooks.
    – Asaf Aviv
    Nov 4 at 7:04












  • For the reference, here is related question but not full duplicate, stackoverflow.com/questions/53062732/…
    – estus
    Nov 5 at 19:59















up vote
0
down vote

favorite
1












React 16.7 has State Hook,so I can use function component instead of class component in any situation,is it right?
https://reactjs.org/docs/hooks-state.html










share|improve this question




















  • 1




    Yep, everything you can do with class components you will be able to do with functional components + hooks.
    – Asaf Aviv
    Nov 4 at 7:04












  • For the reference, here is related question but not full duplicate, stackoverflow.com/questions/53062732/…
    – estus
    Nov 5 at 19:59













up vote
0
down vote

favorite
1









up vote
0
down vote

favorite
1






1





React 16.7 has State Hook,so I can use function component instead of class component in any situation,is it right?
https://reactjs.org/docs/hooks-state.html










share|improve this question















React 16.7 has State Hook,so I can use function component instead of class component in any situation,is it right?
https://reactjs.org/docs/hooks-state.html







javascript reactjs react-hooks






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 7:07









Yangshun Tay

8,42953565




8,42953565










asked Nov 4 at 6:53









zwl1619

94631738




94631738








  • 1




    Yep, everything you can do with class components you will be able to do with functional components + hooks.
    – Asaf Aviv
    Nov 4 at 7:04












  • For the reference, here is related question but not full duplicate, stackoverflow.com/questions/53062732/…
    – estus
    Nov 5 at 19:59














  • 1




    Yep, everything you can do with class components you will be able to do with functional components + hooks.
    – Asaf Aviv
    Nov 4 at 7:04












  • For the reference, here is related question but not full duplicate, stackoverflow.com/questions/53062732/…
    – estus
    Nov 5 at 19:59








1




1




Yep, everything you can do with class components you will be able to do with functional components + hooks.
– Asaf Aviv
Nov 4 at 7:04






Yep, everything you can do with class components you will be able to do with functional components + hooks.
– Asaf Aviv
Nov 4 at 7:04














For the reference, here is related question but not full duplicate, stackoverflow.com/questions/53062732/…
– estus
Nov 5 at 19:59




For the reference, here is related question but not full duplicate, stackoverflow.com/questions/53062732/…
– estus
Nov 5 at 19:59












3 Answers
3






active

oldest

votes

















up vote
2
down vote













Actually,there are some rules when you use hook:Don’t call Hooks inside loops, conditions, or nested functions and Don’t call Hooks from regular JavaScript functions.



You can read these rules and explanation here: https://reactjs.org/docs/hooks-rules.html



And here is the official explaination.




Our goal is for Hooks to cover all use cases for classes as soon as possible. There are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet, but we plan to add them soon.
It is a very early time for Hooks, so some integrations like DevTools support or Flow/TypeScript typings may not be ready yet. Some third-party libraries might also not be compatible with Hooks at the moment.







share|improve this answer






























    up vote
    1
    down vote













    useState hook is intended to be a replacement for this.state in class components:



    this.state = { foo: 1, bar: 2 };


    becomes either



    const [foo, setFoo] = useState(1);
    const [bar, setBar] = useState(2);


    or



    const [state, setState] = useState({ foo: 1, bar: 2 });


    In the second case it should be taken into account that setState won't merge state properties with previous state, unless this is done explicitly:




    Unlike the setState method found in class components, useState does
    not automatically merge update objects. You can replicate this
    behavior by combining the function updater form with object spread
    syntax:



    setState(prevState => ({...prevState, ...updatedValues});



    As another answer explains, the limitation is that the order of useState calls should be the same every time functional component is called because the order is the only way for the framework to identify component states.



    Problems may appear if the state needs to be accessed outside the component for some reasons, e.g. debugging, testing or specific cases. As the documentation explains, a state in functional component is supposed to be tested by its side effects instead of asserting state directly.






    share|improve this answer






























      up vote
      1
      down vote













      You can use React Hooks + functional components for most situations as a substitute for class components, except in need the following situations:




      • Certain lifecycle methods - You need to use getSnapshotBeforeUpdate and componentDidCatch lifecycles. As Dan said, there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate
        and componentDidCatch lifecycles yet.


      • Debuggability - You need good component debuggability. States created using useState do not show up like the usual key-value manner in React Devtools at the moment. It's displayed as the format React uses to internally represent the function's state.


      • Testing - In Enzyme tests, you could manually set the state of components you were testing. You can't do that with state hooks since the state lives outside the component. You also can't assert component states.







      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',
        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%2f53138465%2freact-16-7-has-state-hook-can-i-use-functional-component-instead-of-class-compo%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








        up vote
        2
        down vote













        Actually,there are some rules when you use hook:Don’t call Hooks inside loops, conditions, or nested functions and Don’t call Hooks from regular JavaScript functions.



        You can read these rules and explanation here: https://reactjs.org/docs/hooks-rules.html



        And here is the official explaination.




        Our goal is for Hooks to cover all use cases for classes as soon as possible. There are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet, but we plan to add them soon.
        It is a very early time for Hooks, so some integrations like DevTools support or Flow/TypeScript typings may not be ready yet. Some third-party libraries might also not be compatible with Hooks at the moment.







        share|improve this answer



























          up vote
          2
          down vote













          Actually,there are some rules when you use hook:Don’t call Hooks inside loops, conditions, or nested functions and Don’t call Hooks from regular JavaScript functions.



          You can read these rules and explanation here: https://reactjs.org/docs/hooks-rules.html



          And here is the official explaination.




          Our goal is for Hooks to cover all use cases for classes as soon as possible. There are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet, but we plan to add them soon.
          It is a very early time for Hooks, so some integrations like DevTools support or Flow/TypeScript typings may not be ready yet. Some third-party libraries might also not be compatible with Hooks at the moment.







          share|improve this answer

























            up vote
            2
            down vote










            up vote
            2
            down vote









            Actually,there are some rules when you use hook:Don’t call Hooks inside loops, conditions, or nested functions and Don’t call Hooks from regular JavaScript functions.



            You can read these rules and explanation here: https://reactjs.org/docs/hooks-rules.html



            And here is the official explaination.




            Our goal is for Hooks to cover all use cases for classes as soon as possible. There are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet, but we plan to add them soon.
            It is a very early time for Hooks, so some integrations like DevTools support or Flow/TypeScript typings may not be ready yet. Some third-party libraries might also not be compatible with Hooks at the moment.







            share|improve this answer














            Actually,there are some rules when you use hook:Don’t call Hooks inside loops, conditions, or nested functions and Don’t call Hooks from regular JavaScript functions.



            You can read these rules and explanation here: https://reactjs.org/docs/hooks-rules.html



            And here is the official explaination.




            Our goal is for Hooks to cover all use cases for classes as soon as possible. There are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet, but we plan to add them soon.
            It is a very early time for Hooks, so some integrations like DevTools support or Flow/TypeScript typings may not be ready yet. Some third-party libraries might also not be compatible with Hooks at the moment.








            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 4 at 7:15

























            answered Nov 4 at 7:01









            Root

            1,150128




            1,150128
























                up vote
                1
                down vote













                useState hook is intended to be a replacement for this.state in class components:



                this.state = { foo: 1, bar: 2 };


                becomes either



                const [foo, setFoo] = useState(1);
                const [bar, setBar] = useState(2);


                or



                const [state, setState] = useState({ foo: 1, bar: 2 });


                In the second case it should be taken into account that setState won't merge state properties with previous state, unless this is done explicitly:




                Unlike the setState method found in class components, useState does
                not automatically merge update objects. You can replicate this
                behavior by combining the function updater form with object spread
                syntax:



                setState(prevState => ({...prevState, ...updatedValues});



                As another answer explains, the limitation is that the order of useState calls should be the same every time functional component is called because the order is the only way for the framework to identify component states.



                Problems may appear if the state needs to be accessed outside the component for some reasons, e.g. debugging, testing or specific cases. As the documentation explains, a state in functional component is supposed to be tested by its side effects instead of asserting state directly.






                share|improve this answer



























                  up vote
                  1
                  down vote













                  useState hook is intended to be a replacement for this.state in class components:



                  this.state = { foo: 1, bar: 2 };


                  becomes either



                  const [foo, setFoo] = useState(1);
                  const [bar, setBar] = useState(2);


                  or



                  const [state, setState] = useState({ foo: 1, bar: 2 });


                  In the second case it should be taken into account that setState won't merge state properties with previous state, unless this is done explicitly:




                  Unlike the setState method found in class components, useState does
                  not automatically merge update objects. You can replicate this
                  behavior by combining the function updater form with object spread
                  syntax:



                  setState(prevState => ({...prevState, ...updatedValues});



                  As another answer explains, the limitation is that the order of useState calls should be the same every time functional component is called because the order is the only way for the framework to identify component states.



                  Problems may appear if the state needs to be accessed outside the component for some reasons, e.g. debugging, testing or specific cases. As the documentation explains, a state in functional component is supposed to be tested by its side effects instead of asserting state directly.






                  share|improve this answer

























                    up vote
                    1
                    down vote










                    up vote
                    1
                    down vote









                    useState hook is intended to be a replacement for this.state in class components:



                    this.state = { foo: 1, bar: 2 };


                    becomes either



                    const [foo, setFoo] = useState(1);
                    const [bar, setBar] = useState(2);


                    or



                    const [state, setState] = useState({ foo: 1, bar: 2 });


                    In the second case it should be taken into account that setState won't merge state properties with previous state, unless this is done explicitly:




                    Unlike the setState method found in class components, useState does
                    not automatically merge update objects. You can replicate this
                    behavior by combining the function updater form with object spread
                    syntax:



                    setState(prevState => ({...prevState, ...updatedValues});



                    As another answer explains, the limitation is that the order of useState calls should be the same every time functional component is called because the order is the only way for the framework to identify component states.



                    Problems may appear if the state needs to be accessed outside the component for some reasons, e.g. debugging, testing or specific cases. As the documentation explains, a state in functional component is supposed to be tested by its side effects instead of asserting state directly.






                    share|improve this answer














                    useState hook is intended to be a replacement for this.state in class components:



                    this.state = { foo: 1, bar: 2 };


                    becomes either



                    const [foo, setFoo] = useState(1);
                    const [bar, setBar] = useState(2);


                    or



                    const [state, setState] = useState({ foo: 1, bar: 2 });


                    In the second case it should be taken into account that setState won't merge state properties with previous state, unless this is done explicitly:




                    Unlike the setState method found in class components, useState does
                    not automatically merge update objects. You can replicate this
                    behavior by combining the function updater form with object spread
                    syntax:



                    setState(prevState => ({...prevState, ...updatedValues});



                    As another answer explains, the limitation is that the order of useState calls should be the same every time functional component is called because the order is the only way for the framework to identify component states.



                    Problems may appear if the state needs to be accessed outside the component for some reasons, e.g. debugging, testing or specific cases. As the documentation explains, a state in functional component is supposed to be tested by its side effects instead of asserting state directly.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 5 at 6:55

























                    answered Nov 4 at 8:37









                    estus

                    64.3k2195202




                    64.3k2195202






















                        up vote
                        1
                        down vote













                        You can use React Hooks + functional components for most situations as a substitute for class components, except in need the following situations:




                        • Certain lifecycle methods - You need to use getSnapshotBeforeUpdate and componentDidCatch lifecycles. As Dan said, there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate
                          and componentDidCatch lifecycles yet.


                        • Debuggability - You need good component debuggability. States created using useState do not show up like the usual key-value manner in React Devtools at the moment. It's displayed as the format React uses to internally represent the function's state.


                        • Testing - In Enzyme tests, you could manually set the state of components you were testing. You can't do that with state hooks since the state lives outside the component. You also can't assert component states.







                        share|improve this answer

























                          up vote
                          1
                          down vote













                          You can use React Hooks + functional components for most situations as a substitute for class components, except in need the following situations:




                          • Certain lifecycle methods - You need to use getSnapshotBeforeUpdate and componentDidCatch lifecycles. As Dan said, there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate
                            and componentDidCatch lifecycles yet.


                          • Debuggability - You need good component debuggability. States created using useState do not show up like the usual key-value manner in React Devtools at the moment. It's displayed as the format React uses to internally represent the function's state.


                          • Testing - In Enzyme tests, you could manually set the state of components you were testing. You can't do that with state hooks since the state lives outside the component. You also can't assert component states.







                          share|improve this answer























                            up vote
                            1
                            down vote










                            up vote
                            1
                            down vote









                            You can use React Hooks + functional components for most situations as a substitute for class components, except in need the following situations:




                            • Certain lifecycle methods - You need to use getSnapshotBeforeUpdate and componentDidCatch lifecycles. As Dan said, there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate
                              and componentDidCatch lifecycles yet.


                            • Debuggability - You need good component debuggability. States created using useState do not show up like the usual key-value manner in React Devtools at the moment. It's displayed as the format React uses to internally represent the function's state.


                            • Testing - In Enzyme tests, you could manually set the state of components you were testing. You can't do that with state hooks since the state lives outside the component. You also can't assert component states.







                            share|improve this answer












                            You can use React Hooks + functional components for most situations as a substitute for class components, except in need the following situations:




                            • Certain lifecycle methods - You need to use getSnapshotBeforeUpdate and componentDidCatch lifecycles. As Dan said, there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate
                              and componentDidCatch lifecycles yet.


                            • Debuggability - You need good component debuggability. States created using useState do not show up like the usual key-value manner in React Devtools at the moment. It's displayed as the format React uses to internally represent the function's state.


                            • Testing - In Enzyme tests, you could manually set the state of components you were testing. You can't do that with state hooks since the state lives outside the component. You also can't assert component states.








                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 11 at 7:15









                            Yangshun Tay

                            8,42953565




                            8,42953565






























                                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.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • 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%2f53138465%2freact-16-7-has-state-hook-can-i-use-functional-component-instead-of-class-compo%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

                                Florida Star v. B. J. F.

                                Danny Elfman

                                Lugert, Oklahoma