How can I add React hooks into React `class` component?











up vote
1
down vote

favorite












I have for e.g. this react Class:



class MyDiv extends React.component
constructor(){
this.state={sampleState:'hello world'}
}
render(){
return <div>{this.state.sampleState}
}
}


The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?










share|improve this question


























    up vote
    1
    down vote

    favorite












    I have for e.g. this react Class:



    class MyDiv extends React.component
    constructor(){
    this.state={sampleState:'hello world'}
    }
    render(){
    return <div>{this.state.sampleState}
    }
    }


    The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?










    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I have for e.g. this react Class:



      class MyDiv extends React.component
      constructor(){
      this.state={sampleState:'hello world'}
      }
      render(){
      return <div>{this.state.sampleState}
      }
      }


      The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?










      share|improve this question













      I have for e.g. this react Class:



      class MyDiv extends React.component
      constructor(){
      this.state={sampleState:'hello world'}
      }
      render(){
      return <div>{this.state.sampleState}
      }
      }


      The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?







      javascript reactjs react-hooks






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 4 hours ago









      Aminadav Glickshtein

      7,74733078




      7,74733078
























          4 Answers
          4






          active

          oldest

          votes

















          up vote
          2
          down vote













          Class components don't support hooks -



          According to the Hooks-FAQ:
          You can’t use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.






          share|improve this answer




























            up vote
            1
            down vote













            Hooks are not meant to be used for classes but rather functions. If you wish to use hooks, you can start by writing new code as functional components with hooks



            According to React FAQs




            You can’t use Hooks inside of a class component, but you can
            definitely mix classes and function components with Hooks in a single
            tree. Whether a component is a class or a function that uses Hooks is
            an implementation detail of that component. In the longer term, we
            expect Hooks to be the primary way people write React components.




            const MyDiv = () => {
            const [sampleState, setState] = useState('hello world');
            render(){
            return <div>{sampleState}</div>
            }
            }





            share|improve this answer























            • it should be setSampleState no?
              – Aseem Upadhyay
              4 hours ago










            • Its a simple array destructuring and can be named anything. setState, setSampleState, setABC
              – Shubham Khatri
              4 hours ago










            • alright gotcha.
              – Aseem Upadhyay
              4 hours ago


















            up vote
            1
            down vote













            As other answers already explain, hooks API was designed to provide function components with functionality that currently is available only in class components. Hooks aren't supposed to used in class components.



            Class components can be written to make easier a migration to function components.



            With a single state:



            class MyDiv extends Component {
            state = {sampleState: 'hello world'};

            render(){
            const { state } = this;
            const setState = state => this.setState(state);

            return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
            }
            }


            is converted to



            const MyDiv = () => {
            const [state, setState] = useState({sampleState: 'hello world'});

            return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
            }


            Notice that useState state setter doesn't merge state properties automatically, this should be covered with setState(prevState => ({ ...prevState, foo: 1 }));



            With multiple states:



            class MyDiv extends Component {
            state = {sampleState: 'hello world'};

            render(){
            const { sampleState } = this.state;
            const setSampleState = sampleState => this.setState({ sampleState });

            return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
            }
            }


            is converted to



            const MyDiv = () => {
            const [sampleState, setSampleState] = useState('hello world');

            return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
            }





            share|improve this answer




























              up vote
              0
              down vote













              It won't be possible with your existing class components. You'll have to convert your class component into a functional component and then do something on the lines of -



              function MyDiv() {
              const [sampleState, setSampleState] = useState('hello world');
              return (
              <div>{sampleState}</div>
              )
              }





              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%2f53371356%2fhow-can-i-add-react-hooks-into-react-class-component%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                2
                down vote













                Class components don't support hooks -



                According to the Hooks-FAQ:
                You can’t use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.






                share|improve this answer

























                  up vote
                  2
                  down vote













                  Class components don't support hooks -



                  According to the Hooks-FAQ:
                  You can’t use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.






                  share|improve this answer























                    up vote
                    2
                    down vote










                    up vote
                    2
                    down vote









                    Class components don't support hooks -



                    According to the Hooks-FAQ:
                    You can’t use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.






                    share|improve this answer












                    Class components don't support hooks -



                    According to the Hooks-FAQ:
                    You can’t use Hooks inside of a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 4 hours ago









                    Gilad Bar

                    323110




                    323110
























                        up vote
                        1
                        down vote













                        Hooks are not meant to be used for classes but rather functions. If you wish to use hooks, you can start by writing new code as functional components with hooks



                        According to React FAQs




                        You can’t use Hooks inside of a class component, but you can
                        definitely mix classes and function components with Hooks in a single
                        tree. Whether a component is a class or a function that uses Hooks is
                        an implementation detail of that component. In the longer term, we
                        expect Hooks to be the primary way people write React components.




                        const MyDiv = () => {
                        const [sampleState, setState] = useState('hello world');
                        render(){
                        return <div>{sampleState}</div>
                        }
                        }





                        share|improve this answer























                        • it should be setSampleState no?
                          – Aseem Upadhyay
                          4 hours ago










                        • Its a simple array destructuring and can be named anything. setState, setSampleState, setABC
                          – Shubham Khatri
                          4 hours ago










                        • alright gotcha.
                          – Aseem Upadhyay
                          4 hours ago















                        up vote
                        1
                        down vote













                        Hooks are not meant to be used for classes but rather functions. If you wish to use hooks, you can start by writing new code as functional components with hooks



                        According to React FAQs




                        You can’t use Hooks inside of a class component, but you can
                        definitely mix classes and function components with Hooks in a single
                        tree. Whether a component is a class or a function that uses Hooks is
                        an implementation detail of that component. In the longer term, we
                        expect Hooks to be the primary way people write React components.




                        const MyDiv = () => {
                        const [sampleState, setState] = useState('hello world');
                        render(){
                        return <div>{sampleState}</div>
                        }
                        }





                        share|improve this answer























                        • it should be setSampleState no?
                          – Aseem Upadhyay
                          4 hours ago










                        • Its a simple array destructuring and can be named anything. setState, setSampleState, setABC
                          – Shubham Khatri
                          4 hours ago










                        • alright gotcha.
                          – Aseem Upadhyay
                          4 hours ago













                        up vote
                        1
                        down vote










                        up vote
                        1
                        down vote









                        Hooks are not meant to be used for classes but rather functions. If you wish to use hooks, you can start by writing new code as functional components with hooks



                        According to React FAQs




                        You can’t use Hooks inside of a class component, but you can
                        definitely mix classes and function components with Hooks in a single
                        tree. Whether a component is a class or a function that uses Hooks is
                        an implementation detail of that component. In the longer term, we
                        expect Hooks to be the primary way people write React components.




                        const MyDiv = () => {
                        const [sampleState, setState] = useState('hello world');
                        render(){
                        return <div>{sampleState}</div>
                        }
                        }





                        share|improve this answer














                        Hooks are not meant to be used for classes but rather functions. If you wish to use hooks, you can start by writing new code as functional components with hooks



                        According to React FAQs




                        You can’t use Hooks inside of a class component, but you can
                        definitely mix classes and function components with Hooks in a single
                        tree. Whether a component is a class or a function that uses Hooks is
                        an implementation detail of that component. In the longer term, we
                        expect Hooks to be the primary way people write React components.




                        const MyDiv = () => {
                        const [sampleState, setState] = useState('hello world');
                        render(){
                        return <div>{sampleState}</div>
                        }
                        }






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited 4 hours ago

























                        answered 4 hours ago









                        Shubham Khatri

                        73.9k1382122




                        73.9k1382122












                        • it should be setSampleState no?
                          – Aseem Upadhyay
                          4 hours ago










                        • Its a simple array destructuring and can be named anything. setState, setSampleState, setABC
                          – Shubham Khatri
                          4 hours ago










                        • alright gotcha.
                          – Aseem Upadhyay
                          4 hours ago


















                        • it should be setSampleState no?
                          – Aseem Upadhyay
                          4 hours ago










                        • Its a simple array destructuring and can be named anything. setState, setSampleState, setABC
                          – Shubham Khatri
                          4 hours ago










                        • alright gotcha.
                          – Aseem Upadhyay
                          4 hours ago
















                        it should be setSampleState no?
                        – Aseem Upadhyay
                        4 hours ago




                        it should be setSampleState no?
                        – Aseem Upadhyay
                        4 hours ago












                        Its a simple array destructuring and can be named anything. setState, setSampleState, setABC
                        – Shubham Khatri
                        4 hours ago




                        Its a simple array destructuring and can be named anything. setState, setSampleState, setABC
                        – Shubham Khatri
                        4 hours ago












                        alright gotcha.
                        – Aseem Upadhyay
                        4 hours ago




                        alright gotcha.
                        – Aseem Upadhyay
                        4 hours ago










                        up vote
                        1
                        down vote













                        As other answers already explain, hooks API was designed to provide function components with functionality that currently is available only in class components. Hooks aren't supposed to used in class components.



                        Class components can be written to make easier a migration to function components.



                        With a single state:



                        class MyDiv extends Component {
                        state = {sampleState: 'hello world'};

                        render(){
                        const { state } = this;
                        const setState = state => this.setState(state);

                        return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
                        }
                        }


                        is converted to



                        const MyDiv = () => {
                        const [state, setState] = useState({sampleState: 'hello world'});

                        return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
                        }


                        Notice that useState state setter doesn't merge state properties automatically, this should be covered with setState(prevState => ({ ...prevState, foo: 1 }));



                        With multiple states:



                        class MyDiv extends Component {
                        state = {sampleState: 'hello world'};

                        render(){
                        const { sampleState } = this.state;
                        const setSampleState = sampleState => this.setState({ sampleState });

                        return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
                        }
                        }


                        is converted to



                        const MyDiv = () => {
                        const [sampleState, setSampleState] = useState('hello world');

                        return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
                        }





                        share|improve this answer

























                          up vote
                          1
                          down vote













                          As other answers already explain, hooks API was designed to provide function components with functionality that currently is available only in class components. Hooks aren't supposed to used in class components.



                          Class components can be written to make easier a migration to function components.



                          With a single state:



                          class MyDiv extends Component {
                          state = {sampleState: 'hello world'};

                          render(){
                          const { state } = this;
                          const setState = state => this.setState(state);

                          return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
                          }
                          }


                          is converted to



                          const MyDiv = () => {
                          const [state, setState] = useState({sampleState: 'hello world'});

                          return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
                          }


                          Notice that useState state setter doesn't merge state properties automatically, this should be covered with setState(prevState => ({ ...prevState, foo: 1 }));



                          With multiple states:



                          class MyDiv extends Component {
                          state = {sampleState: 'hello world'};

                          render(){
                          const { sampleState } = this.state;
                          const setSampleState = sampleState => this.setState({ sampleState });

                          return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
                          }
                          }


                          is converted to



                          const MyDiv = () => {
                          const [sampleState, setSampleState] = useState('hello world');

                          return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
                          }





                          share|improve this answer























                            up vote
                            1
                            down vote










                            up vote
                            1
                            down vote









                            As other answers already explain, hooks API was designed to provide function components with functionality that currently is available only in class components. Hooks aren't supposed to used in class components.



                            Class components can be written to make easier a migration to function components.



                            With a single state:



                            class MyDiv extends Component {
                            state = {sampleState: 'hello world'};

                            render(){
                            const { state } = this;
                            const setState = state => this.setState(state);

                            return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
                            }
                            }


                            is converted to



                            const MyDiv = () => {
                            const [state, setState] = useState({sampleState: 'hello world'});

                            return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
                            }


                            Notice that useState state setter doesn't merge state properties automatically, this should be covered with setState(prevState => ({ ...prevState, foo: 1 }));



                            With multiple states:



                            class MyDiv extends Component {
                            state = {sampleState: 'hello world'};

                            render(){
                            const { sampleState } = this.state;
                            const setSampleState = sampleState => this.setState({ sampleState });

                            return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
                            }
                            }


                            is converted to



                            const MyDiv = () => {
                            const [sampleState, setSampleState] = useState('hello world');

                            return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
                            }





                            share|improve this answer












                            As other answers already explain, hooks API was designed to provide function components with functionality that currently is available only in class components. Hooks aren't supposed to used in class components.



                            Class components can be written to make easier a migration to function components.



                            With a single state:



                            class MyDiv extends Component {
                            state = {sampleState: 'hello world'};

                            render(){
                            const { state } = this;
                            const setState = state => this.setState(state);

                            return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
                            }
                            }


                            is converted to



                            const MyDiv = () => {
                            const [state, setState] = useState({sampleState: 'hello world'});

                            return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
                            }


                            Notice that useState state setter doesn't merge state properties automatically, this should be covered with setState(prevState => ({ ...prevState, foo: 1 }));



                            With multiple states:



                            class MyDiv extends Component {
                            state = {sampleState: 'hello world'};

                            render(){
                            const { sampleState } = this.state;
                            const setSampleState = sampleState => this.setState({ sampleState });

                            return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
                            }
                            }


                            is converted to



                            const MyDiv = () => {
                            const [sampleState, setSampleState] = useState('hello world');

                            return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 3 hours ago









                            estus

                            63k2193200




                            63k2193200






















                                up vote
                                0
                                down vote













                                It won't be possible with your existing class components. You'll have to convert your class component into a functional component and then do something on the lines of -



                                function MyDiv() {
                                const [sampleState, setSampleState] = useState('hello world');
                                return (
                                <div>{sampleState}</div>
                                )
                                }





                                share|improve this answer

























                                  up vote
                                  0
                                  down vote













                                  It won't be possible with your existing class components. You'll have to convert your class component into a functional component and then do something on the lines of -



                                  function MyDiv() {
                                  const [sampleState, setSampleState] = useState('hello world');
                                  return (
                                  <div>{sampleState}</div>
                                  )
                                  }





                                  share|improve this answer























                                    up vote
                                    0
                                    down vote










                                    up vote
                                    0
                                    down vote









                                    It won't be possible with your existing class components. You'll have to convert your class component into a functional component and then do something on the lines of -



                                    function MyDiv() {
                                    const [sampleState, setSampleState] = useState('hello world');
                                    return (
                                    <div>{sampleState}</div>
                                    )
                                    }





                                    share|improve this answer












                                    It won't be possible with your existing class components. You'll have to convert your class component into a functional component and then do something on the lines of -



                                    function MyDiv() {
                                    const [sampleState, setSampleState] = useState('hello world');
                                    return (
                                    <div>{sampleState}</div>
                                    )
                                    }






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered 4 hours ago









                                    Aseem Upadhyay

                                    1,021520




                                    1,021520






























                                         

                                        draft saved


                                        draft discarded



















































                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53371356%2fhow-can-i-add-react-hooks-into-react-class-component%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

                                        Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                                        Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                                        A Topological Invariant for $pi_3(U(n))$