Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS lifecycle method inside a function Component

Tags:

reactjs

redux

Instead of writing my components inside a class, I'd like to use the function syntax.

How do I override componentDidMount, componentWillMount inside function 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>       ) } 
like image 913
Aftab Naveed Avatar asked Jun 12 '17 18:06

Aftab Naveed


People also ask

Can we use React lifecycle methods in functional components?

A React component undergoes three different phases in its lifecycle, including mounting, updating, and unmounting. Each phase has specific methods responsible for a particular stage in a component's lifecycle. These methods are technically particular to class-based components and not intended for functional components.

Which React hook is used to handle lifecycle methods in a functional component?

React component lifecycle with hooks You can take advantage of the useEffect hook to achieve the same results as with the componentDidMount, componentDidUpdate and componentWillUnmount methods. useEffect accepts two parameters. The first one is a callback which runs after render, much like in componentDidMount.

Can we use componentDidMount in functional component?

Using componentDidMount in functional components with useEffect. This is how we can perform the equivalent of componentDidMount in functional components using the useEffect Hook: useEffect(() => { // Inside this callback function we perform our side effects. });

Can we use componentDidUpdate in functional component?

ComponentDidUpdate is a React component lifecycle method invoked immediately after a component's updates are flushed to the DOM. This is one of the most used built-in methods, which is not called for the initial render nor applicable to your functional details.


1 Answers

Edit: With the introduction of Hooks it is possible to implement a lifecycle kind of behavior as well as the state in the functional Components. Currently

Hooks are a new feature proposal that lets you use state and other React features without writing a class. They are released in React as a part of v16.8.0

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

Basic syntax:

useEffect(callbackFunction, [dependentProps]) => cleanupFunction 

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, replicating the behavior of componentWillUnmount:

Eg: componentWillUnmount

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

To make useEffect conditional on specific events, you may provide it with an array of values to check for changes:

Eg: componentDidUpdate

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

Hooks Equivalent

useEffect(() => {      // action here }, [props.counter]); // checks for changes in the values in this array 

If you include this array, make sure to include all values from the component scope that change over time (props, state), or you may end up referencing values from previous renders.

There are some subtleties to using useEffect; check out the API Here.


Before v16.7.0

The property of function 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>       )   } } 

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

like image 99
Shubham Khatri Avatar answered Sep 21 '22 11:09

Shubham Khatri