ReactJS lifecycle method inside a functional Component











up vote
29
down vote

favorite
7












Instead of writing my components inside a class, since they are dumb, I mostly write these inside a function.



But how do I override componentDidMount, componentWillMount inside functional components? Is it even possible?



const grid = (props) => {
console.log(props);
let {skuRules} = props;

const componentDidMount = () => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
};
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}









share|improve this question




















  • 1




    I think a reason should be provided for downvoting a question or an answer.
    – Aftab Naveed
    Jun 12 '17 at 21:48










  • I think it's a good question, though the note on classes being dumb is a personal opinion and might have earned the downvoting :)
    – Joehannes
    Oct 13 '17 at 17:02






  • 1




    Understood, but that's the way the REACT community calls it :-)
    – Aftab Naveed
    Oct 19 '17 at 7:20












  • It's always safer inside the herd, but when you reach the edges it starts getting messy ...
    – Joehannes
    Oct 20 '17 at 12:59










  • functional components are not supposed to have lifecycle methods. because they are just functions. and functions don't have methods. there are classes for that
    – avalanche1
    Oct 24 at 11:10















up vote
29
down vote

favorite
7












Instead of writing my components inside a class, since they are dumb, I mostly write these inside a function.



But how do I override componentDidMount, componentWillMount inside functional components? Is it even possible?



const grid = (props) => {
console.log(props);
let {skuRules} = props;

const componentDidMount = () => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
};
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}









share|improve this question




















  • 1




    I think a reason should be provided for downvoting a question or an answer.
    – Aftab Naveed
    Jun 12 '17 at 21:48










  • I think it's a good question, though the note on classes being dumb is a personal opinion and might have earned the downvoting :)
    – Joehannes
    Oct 13 '17 at 17:02






  • 1




    Understood, but that's the way the REACT community calls it :-)
    – Aftab Naveed
    Oct 19 '17 at 7:20












  • It's always safer inside the herd, but when you reach the edges it starts getting messy ...
    – Joehannes
    Oct 20 '17 at 12:59










  • functional components are not supposed to have lifecycle methods. because they are just functions. and functions don't have methods. there are classes for that
    – avalanche1
    Oct 24 at 11:10













up vote
29
down vote

favorite
7









up vote
29
down vote

favorite
7






7





Instead of writing my components inside a class, since they are dumb, I mostly write these inside a function.



But how do I override componentDidMount, componentWillMount inside functional components? Is it even possible?



const grid = (props) => {
console.log(props);
let {skuRules} = props;

const componentDidMount = () => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
};
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}









share|improve this question















Instead of writing my components inside a class, since they are dumb, I mostly write these inside a function.



But how do I override componentDidMount, componentWillMount inside functional components? Is it even possible?



const grid = (props) => {
console.log(props);
let {skuRules} = props;

const componentDidMount = () => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
};
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}






reactjs redux






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago









MeltedPenguin

530515




530515










asked Jun 12 '17 at 18:20









Aftab Naveed

83811027




83811027








  • 1




    I think a reason should be provided for downvoting a question or an answer.
    – Aftab Naveed
    Jun 12 '17 at 21:48










  • I think it's a good question, though the note on classes being dumb is a personal opinion and might have earned the downvoting :)
    – Joehannes
    Oct 13 '17 at 17:02






  • 1




    Understood, but that's the way the REACT community calls it :-)
    – Aftab Naveed
    Oct 19 '17 at 7:20












  • It's always safer inside the herd, but when you reach the edges it starts getting messy ...
    – Joehannes
    Oct 20 '17 at 12:59










  • functional components are not supposed to have lifecycle methods. because they are just functions. and functions don't have methods. there are classes for that
    – avalanche1
    Oct 24 at 11:10














  • 1




    I think a reason should be provided for downvoting a question or an answer.
    – Aftab Naveed
    Jun 12 '17 at 21:48










  • I think it's a good question, though the note on classes being dumb is a personal opinion and might have earned the downvoting :)
    – Joehannes
    Oct 13 '17 at 17:02






  • 1




    Understood, but that's the way the REACT community calls it :-)
    – Aftab Naveed
    Oct 19 '17 at 7:20












  • It's always safer inside the herd, but when you reach the edges it starts getting messy ...
    – Joehannes
    Oct 20 '17 at 12:59










  • functional components are not supposed to have lifecycle methods. because they are just functions. and functions don't have methods. there are classes for that
    – avalanche1
    Oct 24 at 11:10








1




1




I think a reason should be provided for downvoting a question or an answer.
– Aftab Naveed
Jun 12 '17 at 21:48




I think a reason should be provided for downvoting a question or an answer.
– Aftab Naveed
Jun 12 '17 at 21:48












I think it's a good question, though the note on classes being dumb is a personal opinion and might have earned the downvoting :)
– Joehannes
Oct 13 '17 at 17:02




I think it's a good question, though the note on classes being dumb is a personal opinion and might have earned the downvoting :)
– Joehannes
Oct 13 '17 at 17:02




1




1




Understood, but that's the way the REACT community calls it :-)
– Aftab Naveed
Oct 19 '17 at 7:20






Understood, but that's the way the REACT community calls it :-)
– Aftab Naveed
Oct 19 '17 at 7:20














It's always safer inside the herd, but when you reach the edges it starts getting messy ...
– Joehannes
Oct 20 '17 at 12:59




It's always safer inside the herd, but when you reach the edges it starts getting messy ...
– Joehannes
Oct 20 '17 at 12:59












functional components are not supposed to have lifecycle methods. because they are just functions. and functions don't have methods. there are classes for that
– avalanche1
Oct 24 at 11:10




functional components are not supposed to have lifecycle methods. because they are just functions. and functions don't have methods. there are classes for that
– avalanche1
Oct 24 at 11:10












5 Answers
5






active

oldest

votes

















up vote
29
down vote



accepted










You can use react-pure-lifecycle to add lifecycle functions to functional components.



Example:



import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';

const methods = {
componentDidMount(props) {
console.log('I mounted! Here are my props: ', props);
}
};

const Channels = props => (
<h1>Hello</h1>
)

export default lifecycle(methods)(Channels);





share|improve this answer



















  • 1




    This is exactly what I needed and hopefully will make its way to the top of the upvoted comments.
    – JSager
    Mar 25 at 17:02






  • 3




    What is Grid? I don't see it defined anywhere in your code snippet? If you wanted to use redux with this as well could you get away with something like export default lifecycle(methods)(connect({},{})(ComponentName)) ?
    – Sean Clancy
    May 4 at 15:16










  • @SeanClancy Sorry for late response. The code snippet was updated.
    – Yohann
    Jul 10 at 20:15




















up vote
20
down vote













Edit: With the introduction of Hooks its possible to implement lifecycle kind of behaviour as well as state in functional Component. Currently




Hooks are a new feature proposal that lets you use state and other
React features without writing a class. They’re currently in React
v16.7.0-alpha




useEffect hook can be used to replicate lifecycle behaviour, and useState can be used to store state in a functional component.



You can implement your use case in hooks like



const grid = (props) => {
console.log(props);
let {skuRules} = props;

useEffect(() => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
}, ); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour

return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}


useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners. An can be used to replicate the componentWillUnmount behaviour



Eg: componentWillUnmount



useEffect(() => {
window.addEventListener('unhandledRejection', handler);
return () => {
window.removeEventListener('unhandledRejection', handler);
}
}, )


As the second argument if you provide values, these will be compared before triggering the callback if these is any change in any of the following



Eg: componentDidUpdate



componentDidUpdate(prevProps, prevState) {
const { counter } = this.props;
if (this.props.counter !== nextProps.counter) {
// some action here
}
}


Hooks Equivalent



useEffect(() => {
// action here
}, [props.counter]);




Before v16.7.0



The property of functional components is that they don't have access to Reacts lifecycle functions or the this keyword. You need to extend the React.Component class if you want to use the lifecycle function.



class Grid extends React.Component  {
constructor(props) {
super(props)
}

componentDidMount () {
if(!this.props.fetched) {
this.props.fetchRules();
}
console.log('mount it!');
}
render() {
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
}


Functional components are useful when you only want to render your Component without the need of extra logic.






share|improve this answer



















  • 1




    As I said, you have a logic in your component and you requirement wants you to use a lifecycle function and you you cant do that with functioanl components. So better make use of class. Use functional component when your component contains no extra logic
    – Shubham Khatri
    Jun 12 '17 at 18:41










  • Happy to help :), Glad I was able to explain
    – Shubham Khatri
    Jun 12 '17 at 18:59


















up vote
5
down vote













Solution One:
You can use new react HOOKS API. Currently in React v16.7.0-alpha



Hooks let you use more of React’s features without classes.
Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.
Hooks solves all the problems addressed with Recompose.



A Note from the Author of recompose (acdlite, Oct 25 2018):




Hi! I created Recompose about three years ago. About a year after
that, I joined the React team. Today, we announced a proposal for
Hooks. Hooks solves all the problems I attempted to address with
Recompose three years ago, and more on top of that. I will be
discontinuing active maintenance of this package (excluding perhaps
bugfixes or patches for compatibility with future React releases), and
recommending that people use Hooks instead. Your existing code with
Recompose will still work, just don't expect any new features.




Solution Two:



If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a functional component.



Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).



// taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33

function RenderlessComponent() {
return null;
}

export default lifecycle({

componentDidMount() {
const { checkIfAuthed } = this.props;
// Do they have an active session? ("Remember me")
checkIfAuthed();
},

componentWillReceiveProps(nextProps) {
const {
loadUser,
} = this.props;

// Various 'indicators'..
const becameAuthed = (!(this.props.auth) && nextProps.auth);
const isCurrentUser = (this.props.currentUser !== null);

if (becameAuthed) {
loadUser(nextProps.auth.uid);
}

const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
if (shouldSetCurrentUser) {
const currentUser = nextProps.users[nextProps.auth.uid];
if (currentUser) {
this.props.setCurrentUser({
'id': nextProps.auth.uid,
...currentUser,
});
}
}
}
})(RenderlessComponent);





share|improve this answer






























    up vote
    4
    down vote













    If you need use React LifeCycle, you need use Class.



    Sample:



    import React, { Component } from 'react';

    class Grid extends Component {

    constructor(props){
    super(props)
    }

    componentDidMount () { /* do something */ }

    render () {
    return <h1>Hello</h1>
    }

    }





    share|improve this answer





















    • I don't want to use the class.
      – Aftab Naveed
      Jun 12 '17 at 18:34






    • 1




      But, componentDidMount just work in class :/
      – Gabriel Ferreira
      Jun 12 '17 at 18:35






    • 1




      hmm makes sense thank you.
      – Aftab Naveed
      Jun 12 '17 at 18:59










    • You're welcome :D
      – Gabriel Ferreira
      Jun 12 '17 at 20:15


















    up vote
    0
    down vote













    You can make use of create-react-class module.
    Official documentation



    Of course you must first install it



    npm install create-react-class


    Here is a working example



    import React from "react";
    import ReactDOM from "react-dom"
    let createReactClass = require('create-react-class')


    let Clock = createReactClass({
    getInitialState:function(){
    return {date:new Date()}
    },

    render:function(){
    return (
    <h1>{this.state.date.toLocaleTimeString()}</h1>
    )
    },

    componentDidMount:function(){
    this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
    },

    componentWillUnmount:function(){
    clearInterval(this.timerId)
    }

    })

    ReactDOM.render(
    <Clock/>,
    document.getElementById('root')
    )





    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%2f44506207%2freactjs-lifecycle-method-inside-a-functional-component%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      29
      down vote



      accepted










      You can use react-pure-lifecycle to add lifecycle functions to functional components.



      Example:



      import React, { Component } from 'react';
      import lifecycle from 'react-pure-lifecycle';

      const methods = {
      componentDidMount(props) {
      console.log('I mounted! Here are my props: ', props);
      }
      };

      const Channels = props => (
      <h1>Hello</h1>
      )

      export default lifecycle(methods)(Channels);





      share|improve this answer



















      • 1




        This is exactly what I needed and hopefully will make its way to the top of the upvoted comments.
        – JSager
        Mar 25 at 17:02






      • 3




        What is Grid? I don't see it defined anywhere in your code snippet? If you wanted to use redux with this as well could you get away with something like export default lifecycle(methods)(connect({},{})(ComponentName)) ?
        – Sean Clancy
        May 4 at 15:16










      • @SeanClancy Sorry for late response. The code snippet was updated.
        – Yohann
        Jul 10 at 20:15

















      up vote
      29
      down vote



      accepted










      You can use react-pure-lifecycle to add lifecycle functions to functional components.



      Example:



      import React, { Component } from 'react';
      import lifecycle from 'react-pure-lifecycle';

      const methods = {
      componentDidMount(props) {
      console.log('I mounted! Here are my props: ', props);
      }
      };

      const Channels = props => (
      <h1>Hello</h1>
      )

      export default lifecycle(methods)(Channels);





      share|improve this answer



















      • 1




        This is exactly what I needed and hopefully will make its way to the top of the upvoted comments.
        – JSager
        Mar 25 at 17:02






      • 3




        What is Grid? I don't see it defined anywhere in your code snippet? If you wanted to use redux with this as well could you get away with something like export default lifecycle(methods)(connect({},{})(ComponentName)) ?
        – Sean Clancy
        May 4 at 15:16










      • @SeanClancy Sorry for late response. The code snippet was updated.
        – Yohann
        Jul 10 at 20:15















      up vote
      29
      down vote



      accepted







      up vote
      29
      down vote



      accepted






      You can use react-pure-lifecycle to add lifecycle functions to functional components.



      Example:



      import React, { Component } from 'react';
      import lifecycle from 'react-pure-lifecycle';

      const methods = {
      componentDidMount(props) {
      console.log('I mounted! Here are my props: ', props);
      }
      };

      const Channels = props => (
      <h1>Hello</h1>
      )

      export default lifecycle(methods)(Channels);





      share|improve this answer














      You can use react-pure-lifecycle to add lifecycle functions to functional components.



      Example:



      import React, { Component } from 'react';
      import lifecycle from 'react-pure-lifecycle';

      const methods = {
      componentDidMount(props) {
      console.log('I mounted! Here are my props: ', props);
      }
      };

      const Channels = props => (
      <h1>Hello</h1>
      )

      export default lifecycle(methods)(Channels);






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jul 6 at 3:57









      Arturo Volpe

      2,54731834




      2,54731834










      answered Jan 15 at 14:04









      Yohann

      41658




      41658








      • 1




        This is exactly what I needed and hopefully will make its way to the top of the upvoted comments.
        – JSager
        Mar 25 at 17:02






      • 3




        What is Grid? I don't see it defined anywhere in your code snippet? If you wanted to use redux with this as well could you get away with something like export default lifecycle(methods)(connect({},{})(ComponentName)) ?
        – Sean Clancy
        May 4 at 15:16










      • @SeanClancy Sorry for late response. The code snippet was updated.
        – Yohann
        Jul 10 at 20:15
















      • 1




        This is exactly what I needed and hopefully will make its way to the top of the upvoted comments.
        – JSager
        Mar 25 at 17:02






      • 3




        What is Grid? I don't see it defined anywhere in your code snippet? If you wanted to use redux with this as well could you get away with something like export default lifecycle(methods)(connect({},{})(ComponentName)) ?
        – Sean Clancy
        May 4 at 15:16










      • @SeanClancy Sorry for late response. The code snippet was updated.
        – Yohann
        Jul 10 at 20:15










      1




      1




      This is exactly what I needed and hopefully will make its way to the top of the upvoted comments.
      – JSager
      Mar 25 at 17:02




      This is exactly what I needed and hopefully will make its way to the top of the upvoted comments.
      – JSager
      Mar 25 at 17:02




      3




      3




      What is Grid? I don't see it defined anywhere in your code snippet? If you wanted to use redux with this as well could you get away with something like export default lifecycle(methods)(connect({},{})(ComponentName)) ?
      – Sean Clancy
      May 4 at 15:16




      What is Grid? I don't see it defined anywhere in your code snippet? If you wanted to use redux with this as well could you get away with something like export default lifecycle(methods)(connect({},{})(ComponentName)) ?
      – Sean Clancy
      May 4 at 15:16












      @SeanClancy Sorry for late response. The code snippet was updated.
      – Yohann
      Jul 10 at 20:15






      @SeanClancy Sorry for late response. The code snippet was updated.
      – Yohann
      Jul 10 at 20:15














      up vote
      20
      down vote













      Edit: With the introduction of Hooks its possible to implement lifecycle kind of behaviour as well as state in functional Component. Currently




      Hooks are a new feature proposal that lets you use state and other
      React features without writing a class. They’re currently in React
      v16.7.0-alpha




      useEffect hook can be used to replicate lifecycle behaviour, and useState can be used to store state in a functional component.



      You can implement your use case in hooks like



      const grid = (props) => {
      console.log(props);
      let {skuRules} = props;

      useEffect(() => {
      if(!props.fetched) {
      props.fetchRules();
      }
      console.log('mount it!');
      }, ); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour

      return(
      <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
      <Box title="Sku Promotion">
      <ActionButtons buttons={actionButtons} />
      <SkuRuleGrid
      data={skuRules.payload}
      fetch={props.fetchSkuRules}
      />
      </Box>
      </Content>
      )
      }


      useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners. An can be used to replicate the componentWillUnmount behaviour



      Eg: componentWillUnmount



      useEffect(() => {
      window.addEventListener('unhandledRejection', handler);
      return () => {
      window.removeEventListener('unhandledRejection', handler);
      }
      }, )


      As the second argument if you provide values, these will be compared before triggering the callback if these is any change in any of the following



      Eg: componentDidUpdate



      componentDidUpdate(prevProps, prevState) {
      const { counter } = this.props;
      if (this.props.counter !== nextProps.counter) {
      // some action here
      }
      }


      Hooks Equivalent



      useEffect(() => {
      // action here
      }, [props.counter]);




      Before v16.7.0



      The property of functional components is that they don't have access to Reacts lifecycle functions or the this keyword. You need to extend the React.Component class if you want to use the lifecycle function.



      class Grid extends React.Component  {
      constructor(props) {
      super(props)
      }

      componentDidMount () {
      if(!this.props.fetched) {
      this.props.fetchRules();
      }
      console.log('mount it!');
      }
      render() {
      return(
      <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
      <Box title="Sku Promotion">
      <ActionButtons buttons={actionButtons} />
      <SkuRuleGrid
      data={skuRules.payload}
      fetch={props.fetchSkuRules}
      />
      </Box>
      </Content>
      )
      }
      }


      Functional components are useful when you only want to render your Component without the need of extra logic.






      share|improve this answer



















      • 1




        As I said, you have a logic in your component and you requirement wants you to use a lifecycle function and you you cant do that with functioanl components. So better make use of class. Use functional component when your component contains no extra logic
        – Shubham Khatri
        Jun 12 '17 at 18:41










      • Happy to help :), Glad I was able to explain
        – Shubham Khatri
        Jun 12 '17 at 18:59















      up vote
      20
      down vote













      Edit: With the introduction of Hooks its possible to implement lifecycle kind of behaviour as well as state in functional Component. Currently




      Hooks are a new feature proposal that lets you use state and other
      React features without writing a class. They’re currently in React
      v16.7.0-alpha




      useEffect hook can be used to replicate lifecycle behaviour, and useState can be used to store state in a functional component.



      You can implement your use case in hooks like



      const grid = (props) => {
      console.log(props);
      let {skuRules} = props;

      useEffect(() => {
      if(!props.fetched) {
      props.fetchRules();
      }
      console.log('mount it!');
      }, ); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour

      return(
      <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
      <Box title="Sku Promotion">
      <ActionButtons buttons={actionButtons} />
      <SkuRuleGrid
      data={skuRules.payload}
      fetch={props.fetchSkuRules}
      />
      </Box>
      </Content>
      )
      }


      useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners. An can be used to replicate the componentWillUnmount behaviour



      Eg: componentWillUnmount



      useEffect(() => {
      window.addEventListener('unhandledRejection', handler);
      return () => {
      window.removeEventListener('unhandledRejection', handler);
      }
      }, )


      As the second argument if you provide values, these will be compared before triggering the callback if these is any change in any of the following



      Eg: componentDidUpdate



      componentDidUpdate(prevProps, prevState) {
      const { counter } = this.props;
      if (this.props.counter !== nextProps.counter) {
      // some action here
      }
      }


      Hooks Equivalent



      useEffect(() => {
      // action here
      }, [props.counter]);




      Before v16.7.0



      The property of functional components is that they don't have access to Reacts lifecycle functions or the this keyword. You need to extend the React.Component class if you want to use the lifecycle function.



      class Grid extends React.Component  {
      constructor(props) {
      super(props)
      }

      componentDidMount () {
      if(!this.props.fetched) {
      this.props.fetchRules();
      }
      console.log('mount it!');
      }
      render() {
      return(
      <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
      <Box title="Sku Promotion">
      <ActionButtons buttons={actionButtons} />
      <SkuRuleGrid
      data={skuRules.payload}
      fetch={props.fetchSkuRules}
      />
      </Box>
      </Content>
      )
      }
      }


      Functional components are useful when you only want to render your Component without the need of extra logic.






      share|improve this answer



















      • 1




        As I said, you have a logic in your component and you requirement wants you to use a lifecycle function and you you cant do that with functioanl components. So better make use of class. Use functional component when your component contains no extra logic
        – Shubham Khatri
        Jun 12 '17 at 18:41










      • Happy to help :), Glad I was able to explain
        – Shubham Khatri
        Jun 12 '17 at 18:59













      up vote
      20
      down vote










      up vote
      20
      down vote









      Edit: With the introduction of Hooks its possible to implement lifecycle kind of behaviour as well as state in functional Component. Currently




      Hooks are a new feature proposal that lets you use state and other
      React features without writing a class. They’re currently in React
      v16.7.0-alpha




      useEffect hook can be used to replicate lifecycle behaviour, and useState can be used to store state in a functional component.



      You can implement your use case in hooks like



      const grid = (props) => {
      console.log(props);
      let {skuRules} = props;

      useEffect(() => {
      if(!props.fetched) {
      props.fetchRules();
      }
      console.log('mount it!');
      }, ); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour

      return(
      <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
      <Box title="Sku Promotion">
      <ActionButtons buttons={actionButtons} />
      <SkuRuleGrid
      data={skuRules.payload}
      fetch={props.fetchSkuRules}
      />
      </Box>
      </Content>
      )
      }


      useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners. An can be used to replicate the componentWillUnmount behaviour



      Eg: componentWillUnmount



      useEffect(() => {
      window.addEventListener('unhandledRejection', handler);
      return () => {
      window.removeEventListener('unhandledRejection', handler);
      }
      }, )


      As the second argument if you provide values, these will be compared before triggering the callback if these is any change in any of the following



      Eg: componentDidUpdate



      componentDidUpdate(prevProps, prevState) {
      const { counter } = this.props;
      if (this.props.counter !== nextProps.counter) {
      // some action here
      }
      }


      Hooks Equivalent



      useEffect(() => {
      // action here
      }, [props.counter]);




      Before v16.7.0



      The property of functional components is that they don't have access to Reacts lifecycle functions or the this keyword. You need to extend the React.Component class if you want to use the lifecycle function.



      class Grid extends React.Component  {
      constructor(props) {
      super(props)
      }

      componentDidMount () {
      if(!this.props.fetched) {
      this.props.fetchRules();
      }
      console.log('mount it!');
      }
      render() {
      return(
      <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
      <Box title="Sku Promotion">
      <ActionButtons buttons={actionButtons} />
      <SkuRuleGrid
      data={skuRules.payload}
      fetch={props.fetchSkuRules}
      />
      </Box>
      </Content>
      )
      }
      }


      Functional components are useful when you only want to render your Component without the need of extra logic.






      share|improve this answer














      Edit: With the introduction of Hooks its possible to implement lifecycle kind of behaviour as well as state in functional Component. Currently




      Hooks are a new feature proposal that lets you use state and other
      React features without writing a class. They’re currently in React
      v16.7.0-alpha




      useEffect hook can be used to replicate lifecycle behaviour, and useState can be used to store state in a functional component.



      You can implement your use case in hooks like



      const grid = (props) => {
      console.log(props);
      let {skuRules} = props;

      useEffect(() => {
      if(!props.fetched) {
      props.fetchRules();
      }
      console.log('mount it!');
      }, ); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour

      return(
      <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
      <Box title="Sku Promotion">
      <ActionButtons buttons={actionButtons} />
      <SkuRuleGrid
      data={skuRules.payload}
      fetch={props.fetchSkuRules}
      />
      </Box>
      </Content>
      )
      }


      useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners. An can be used to replicate the componentWillUnmount behaviour



      Eg: componentWillUnmount



      useEffect(() => {
      window.addEventListener('unhandledRejection', handler);
      return () => {
      window.removeEventListener('unhandledRejection', handler);
      }
      }, )


      As the second argument if you provide values, these will be compared before triggering the callback if these is any change in any of the following



      Eg: componentDidUpdate



      componentDidUpdate(prevProps, prevState) {
      const { counter } = this.props;
      if (this.props.counter !== nextProps.counter) {
      // some action here
      }
      }


      Hooks Equivalent



      useEffect(() => {
      // action here
      }, [props.counter]);




      Before v16.7.0



      The property of functional components is that they don't have access to Reacts lifecycle functions or the this keyword. You need to extend the React.Component class if you want to use the lifecycle function.



      class Grid extends React.Component  {
      constructor(props) {
      super(props)
      }

      componentDidMount () {
      if(!this.props.fetched) {
      this.props.fetchRules();
      }
      console.log('mount it!');
      }
      render() {
      return(
      <Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
      <Box title="Sku Promotion">
      <ActionButtons buttons={actionButtons} />
      <SkuRuleGrid
      data={skuRules.payload}
      fetch={props.fetchSkuRules}
      />
      </Box>
      </Content>
      )
      }
      }


      Functional components are useful when you only want to render your Component without the need of extra logic.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 28 at 8:52

























      answered Jun 12 '17 at 18:22









      Shubham Khatri

      77k1490126




      77k1490126








      • 1




        As I said, you have a logic in your component and you requirement wants you to use a lifecycle function and you you cant do that with functioanl components. So better make use of class. Use functional component when your component contains no extra logic
        – Shubham Khatri
        Jun 12 '17 at 18:41










      • Happy to help :), Glad I was able to explain
        – Shubham Khatri
        Jun 12 '17 at 18:59














      • 1




        As I said, you have a logic in your component and you requirement wants you to use a lifecycle function and you you cant do that with functioanl components. So better make use of class. Use functional component when your component contains no extra logic
        – Shubham Khatri
        Jun 12 '17 at 18:41










      • Happy to help :), Glad I was able to explain
        – Shubham Khatri
        Jun 12 '17 at 18:59








      1




      1




      As I said, you have a logic in your component and you requirement wants you to use a lifecycle function and you you cant do that with functioanl components. So better make use of class. Use functional component when your component contains no extra logic
      – Shubham Khatri
      Jun 12 '17 at 18:41




      As I said, you have a logic in your component and you requirement wants you to use a lifecycle function and you you cant do that with functioanl components. So better make use of class. Use functional component when your component contains no extra logic
      – Shubham Khatri
      Jun 12 '17 at 18:41












      Happy to help :), Glad I was able to explain
      – Shubham Khatri
      Jun 12 '17 at 18:59




      Happy to help :), Glad I was able to explain
      – Shubham Khatri
      Jun 12 '17 at 18:59










      up vote
      5
      down vote













      Solution One:
      You can use new react HOOKS API. Currently in React v16.7.0-alpha



      Hooks let you use more of React’s features without classes.
      Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.
      Hooks solves all the problems addressed with Recompose.



      A Note from the Author of recompose (acdlite, Oct 25 2018):




      Hi! I created Recompose about three years ago. About a year after
      that, I joined the React team. Today, we announced a proposal for
      Hooks. Hooks solves all the problems I attempted to address with
      Recompose three years ago, and more on top of that. I will be
      discontinuing active maintenance of this package (excluding perhaps
      bugfixes or patches for compatibility with future React releases), and
      recommending that people use Hooks instead. Your existing code with
      Recompose will still work, just don't expect any new features.




      Solution Two:



      If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a functional component.



      Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).



      // taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33

      function RenderlessComponent() {
      return null;
      }

      export default lifecycle({

      componentDidMount() {
      const { checkIfAuthed } = this.props;
      // Do they have an active session? ("Remember me")
      checkIfAuthed();
      },

      componentWillReceiveProps(nextProps) {
      const {
      loadUser,
      } = this.props;

      // Various 'indicators'..
      const becameAuthed = (!(this.props.auth) && nextProps.auth);
      const isCurrentUser = (this.props.currentUser !== null);

      if (becameAuthed) {
      loadUser(nextProps.auth.uid);
      }

      const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
      if (shouldSetCurrentUser) {
      const currentUser = nextProps.users[nextProps.auth.uid];
      if (currentUser) {
      this.props.setCurrentUser({
      'id': nextProps.auth.uid,
      ...currentUser,
      });
      }
      }
      }
      })(RenderlessComponent);





      share|improve this answer



























        up vote
        5
        down vote













        Solution One:
        You can use new react HOOKS API. Currently in React v16.7.0-alpha



        Hooks let you use more of React’s features without classes.
        Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.
        Hooks solves all the problems addressed with Recompose.



        A Note from the Author of recompose (acdlite, Oct 25 2018):




        Hi! I created Recompose about three years ago. About a year after
        that, I joined the React team. Today, we announced a proposal for
        Hooks. Hooks solves all the problems I attempted to address with
        Recompose three years ago, and more on top of that. I will be
        discontinuing active maintenance of this package (excluding perhaps
        bugfixes or patches for compatibility with future React releases), and
        recommending that people use Hooks instead. Your existing code with
        Recompose will still work, just don't expect any new features.




        Solution Two:



        If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a functional component.



        Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).



        // taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33

        function RenderlessComponent() {
        return null;
        }

        export default lifecycle({

        componentDidMount() {
        const { checkIfAuthed } = this.props;
        // Do they have an active session? ("Remember me")
        checkIfAuthed();
        },

        componentWillReceiveProps(nextProps) {
        const {
        loadUser,
        } = this.props;

        // Various 'indicators'..
        const becameAuthed = (!(this.props.auth) && nextProps.auth);
        const isCurrentUser = (this.props.currentUser !== null);

        if (becameAuthed) {
        loadUser(nextProps.auth.uid);
        }

        const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
        if (shouldSetCurrentUser) {
        const currentUser = nextProps.users[nextProps.auth.uid];
        if (currentUser) {
        this.props.setCurrentUser({
        'id': nextProps.auth.uid,
        ...currentUser,
        });
        }
        }
        }
        })(RenderlessComponent);





        share|improve this answer

























          up vote
          5
          down vote










          up vote
          5
          down vote









          Solution One:
          You can use new react HOOKS API. Currently in React v16.7.0-alpha



          Hooks let you use more of React’s features without classes.
          Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.
          Hooks solves all the problems addressed with Recompose.



          A Note from the Author of recompose (acdlite, Oct 25 2018):




          Hi! I created Recompose about three years ago. About a year after
          that, I joined the React team. Today, we announced a proposal for
          Hooks. Hooks solves all the problems I attempted to address with
          Recompose three years ago, and more on top of that. I will be
          discontinuing active maintenance of this package (excluding perhaps
          bugfixes or patches for compatibility with future React releases), and
          recommending that people use Hooks instead. Your existing code with
          Recompose will still work, just don't expect any new features.




          Solution Two:



          If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a functional component.



          Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).



          // taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33

          function RenderlessComponent() {
          return null;
          }

          export default lifecycle({

          componentDidMount() {
          const { checkIfAuthed } = this.props;
          // Do they have an active session? ("Remember me")
          checkIfAuthed();
          },

          componentWillReceiveProps(nextProps) {
          const {
          loadUser,
          } = this.props;

          // Various 'indicators'..
          const becameAuthed = (!(this.props.auth) && nextProps.auth);
          const isCurrentUser = (this.props.currentUser !== null);

          if (becameAuthed) {
          loadUser(nextProps.auth.uid);
          }

          const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
          if (shouldSetCurrentUser) {
          const currentUser = nextProps.users[nextProps.auth.uid];
          if (currentUser) {
          this.props.setCurrentUser({
          'id': nextProps.auth.uid,
          ...currentUser,
          });
          }
          }
          }
          })(RenderlessComponent);





          share|improve this answer














          Solution One:
          You can use new react HOOKS API. Currently in React v16.7.0-alpha



          Hooks let you use more of React’s features without classes.
          Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.
          Hooks solves all the problems addressed with Recompose.



          A Note from the Author of recompose (acdlite, Oct 25 2018):




          Hi! I created Recompose about three years ago. About a year after
          that, I joined the React team. Today, we announced a proposal for
          Hooks. Hooks solves all the problems I attempted to address with
          Recompose three years ago, and more on top of that. I will be
          discontinuing active maintenance of this package (excluding perhaps
          bugfixes or patches for compatibility with future React releases), and
          recommending that people use Hooks instead. Your existing code with
          Recompose will still work, just don't expect any new features.




          Solution Two:



          If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a functional component.



          Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).



          // taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33

          function RenderlessComponent() {
          return null;
          }

          export default lifecycle({

          componentDidMount() {
          const { checkIfAuthed } = this.props;
          // Do they have an active session? ("Remember me")
          checkIfAuthed();
          },

          componentWillReceiveProps(nextProps) {
          const {
          loadUser,
          } = this.props;

          // Various 'indicators'..
          const becameAuthed = (!(this.props.auth) && nextProps.auth);
          const isCurrentUser = (this.props.currentUser !== null);

          if (becameAuthed) {
          loadUser(nextProps.auth.uid);
          }

          const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
          if (shouldSetCurrentUser) {
          const currentUser = nextProps.users[nextProps.auth.uid];
          if (currentUser) {
          this.props.setCurrentUser({
          'id': nextProps.auth.uid,
          ...currentUser,
          });
          }
          }
          }
          })(RenderlessComponent);






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 22 at 5:27

























          answered Oct 29 at 12:48









          Shivam

          1,0721228




          1,0721228






















              up vote
              4
              down vote













              If you need use React LifeCycle, you need use Class.



              Sample:



              import React, { Component } from 'react';

              class Grid extends Component {

              constructor(props){
              super(props)
              }

              componentDidMount () { /* do something */ }

              render () {
              return <h1>Hello</h1>
              }

              }





              share|improve this answer





















              • I don't want to use the class.
                – Aftab Naveed
                Jun 12 '17 at 18:34






              • 1




                But, componentDidMount just work in class :/
                – Gabriel Ferreira
                Jun 12 '17 at 18:35






              • 1




                hmm makes sense thank you.
                – Aftab Naveed
                Jun 12 '17 at 18:59










              • You're welcome :D
                – Gabriel Ferreira
                Jun 12 '17 at 20:15















              up vote
              4
              down vote













              If you need use React LifeCycle, you need use Class.



              Sample:



              import React, { Component } from 'react';

              class Grid extends Component {

              constructor(props){
              super(props)
              }

              componentDidMount () { /* do something */ }

              render () {
              return <h1>Hello</h1>
              }

              }





              share|improve this answer





















              • I don't want to use the class.
                – Aftab Naveed
                Jun 12 '17 at 18:34






              • 1




                But, componentDidMount just work in class :/
                – Gabriel Ferreira
                Jun 12 '17 at 18:35






              • 1




                hmm makes sense thank you.
                – Aftab Naveed
                Jun 12 '17 at 18:59










              • You're welcome :D
                – Gabriel Ferreira
                Jun 12 '17 at 20:15













              up vote
              4
              down vote










              up vote
              4
              down vote









              If you need use React LifeCycle, you need use Class.



              Sample:



              import React, { Component } from 'react';

              class Grid extends Component {

              constructor(props){
              super(props)
              }

              componentDidMount () { /* do something */ }

              render () {
              return <h1>Hello</h1>
              }

              }





              share|improve this answer












              If you need use React LifeCycle, you need use Class.



              Sample:



              import React, { Component } from 'react';

              class Grid extends Component {

              constructor(props){
              super(props)
              }

              componentDidMount () { /* do something */ }

              render () {
              return <h1>Hello</h1>
              }

              }






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jun 12 '17 at 18:24









              Gabriel Ferreira

              31014




              31014












              • I don't want to use the class.
                – Aftab Naveed
                Jun 12 '17 at 18:34






              • 1




                But, componentDidMount just work in class :/
                – Gabriel Ferreira
                Jun 12 '17 at 18:35






              • 1




                hmm makes sense thank you.
                – Aftab Naveed
                Jun 12 '17 at 18:59










              • You're welcome :D
                – Gabriel Ferreira
                Jun 12 '17 at 20:15


















              • I don't want to use the class.
                – Aftab Naveed
                Jun 12 '17 at 18:34






              • 1




                But, componentDidMount just work in class :/
                – Gabriel Ferreira
                Jun 12 '17 at 18:35






              • 1




                hmm makes sense thank you.
                – Aftab Naveed
                Jun 12 '17 at 18:59










              • You're welcome :D
                – Gabriel Ferreira
                Jun 12 '17 at 20:15
















              I don't want to use the class.
              – Aftab Naveed
              Jun 12 '17 at 18:34




              I don't want to use the class.
              – Aftab Naveed
              Jun 12 '17 at 18:34




              1




              1




              But, componentDidMount just work in class :/
              – Gabriel Ferreira
              Jun 12 '17 at 18:35




              But, componentDidMount just work in class :/
              – Gabriel Ferreira
              Jun 12 '17 at 18:35




              1




              1




              hmm makes sense thank you.
              – Aftab Naveed
              Jun 12 '17 at 18:59




              hmm makes sense thank you.
              – Aftab Naveed
              Jun 12 '17 at 18:59












              You're welcome :D
              – Gabriel Ferreira
              Jun 12 '17 at 20:15




              You're welcome :D
              – Gabriel Ferreira
              Jun 12 '17 at 20:15










              up vote
              0
              down vote













              You can make use of create-react-class module.
              Official documentation



              Of course you must first install it



              npm install create-react-class


              Here is a working example



              import React from "react";
              import ReactDOM from "react-dom"
              let createReactClass = require('create-react-class')


              let Clock = createReactClass({
              getInitialState:function(){
              return {date:new Date()}
              },

              render:function(){
              return (
              <h1>{this.state.date.toLocaleTimeString()}</h1>
              )
              },

              componentDidMount:function(){
              this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
              },

              componentWillUnmount:function(){
              clearInterval(this.timerId)
              }

              })

              ReactDOM.render(
              <Clock/>,
              document.getElementById('root')
              )





              share|improve this answer

























                up vote
                0
                down vote













                You can make use of create-react-class module.
                Official documentation



                Of course you must first install it



                npm install create-react-class


                Here is a working example



                import React from "react";
                import ReactDOM from "react-dom"
                let createReactClass = require('create-react-class')


                let Clock = createReactClass({
                getInitialState:function(){
                return {date:new Date()}
                },

                render:function(){
                return (
                <h1>{this.state.date.toLocaleTimeString()}</h1>
                )
                },

                componentDidMount:function(){
                this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
                },

                componentWillUnmount:function(){
                clearInterval(this.timerId)
                }

                })

                ReactDOM.render(
                <Clock/>,
                document.getElementById('root')
                )





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  You can make use of create-react-class module.
                  Official documentation



                  Of course you must first install it



                  npm install create-react-class


                  Here is a working example



                  import React from "react";
                  import ReactDOM from "react-dom"
                  let createReactClass = require('create-react-class')


                  let Clock = createReactClass({
                  getInitialState:function(){
                  return {date:new Date()}
                  },

                  render:function(){
                  return (
                  <h1>{this.state.date.toLocaleTimeString()}</h1>
                  )
                  },

                  componentDidMount:function(){
                  this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
                  },

                  componentWillUnmount:function(){
                  clearInterval(this.timerId)
                  }

                  })

                  ReactDOM.render(
                  <Clock/>,
                  document.getElementById('root')
                  )





                  share|improve this answer












                  You can make use of create-react-class module.
                  Official documentation



                  Of course you must first install it



                  npm install create-react-class


                  Here is a working example



                  import React from "react";
                  import ReactDOM from "react-dom"
                  let createReactClass = require('create-react-class')


                  let Clock = createReactClass({
                  getInitialState:function(){
                  return {date:new Date()}
                  },

                  render:function(){
                  return (
                  <h1>{this.state.date.toLocaleTimeString()}</h1>
                  )
                  },

                  componentDidMount:function(){
                  this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
                  },

                  componentWillUnmount:function(){
                  clearInterval(this.timerId)
                  }

                  })

                  ReactDOM.render(
                  <Clock/>,
                  document.getElementById('root')
                  )






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Oct 29 at 12:36









                  Chandan Purohit

                  79889




                  79889






























                      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%2f44506207%2freactjs-lifecycle-method-inside-a-functional-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

                      Basket-ball féminin

                      Different font size/position of beamer's navigation symbols template's content depending on regular/plain...

                      I want to find a topological embedding $f : X rightarrow Y$ and $g: Y rightarrow X$, yet $X$ is not...