Instead of writing my components inside a class, I'd like to use the functional syntax instead.
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>
)
}
if you using react 16.8 you can use react Hooks... React Hooks are functions that let you “hook into” React state and lifecycle features from function components... docs
You can use react-pure-lifecycle to add lifecycle functions to functional components.
Example:
Solution One: You can use new react HOOKS API. Currently in React v16.8.0
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):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 userecompose
for attachinglifecycle hooks, state, handlers etc
to a functional component.Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).
If you need use React LifeCycle, you need use Class.
Sample:
Edit: With the introduction of
Hooks
its possible to implement lifecycle kind of behaviour as well as state in functional Component. CurrentlyuseEffect
hook can be used to replicate lifecycle behaviour, anduseState
can be used to store state in a functional component.You can implement your use case in hooks like
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 thecomponentWillUnmount
behaviourEg: componentWillUnmount
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
Hooks Equivalent
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 theReact.Component
class if you want to use the lifecycle function.Functional components are useful when you only want to render your Component without the need of extra logic.
According to the documentation:
see React documentation