Premise
If you don't need to maintain state, it's prefer to use function component than class component.
But, If you've already implemented class component, you also need to know how to change it.
I also implemented a class component using MobX ( and HOC( Higher Order Component ) ).
The example as below is a sample to change from a class component which using MobX to a function component.
Code
The sample code (class component) before the change is as follows.
The sample code (function component) after the change is as follows.
The points of chage are as follows.
i) replace MobX's @inject and @observer to inject() and useObserver()
@inject('aStore', 'bStore') @observer class SomeComponent extends React.Component { : } const component = withCommonProps(SomeComponent); export default component;
change as below.
const SomeComponent = ({ aStore, bStore, }) => { return useObserver(() => ( : )); }; const component = withCommonProps(inject('aStore', 'bStore')(SomeComponent)); export default component;
ii) replace render() to return useObserver()
class SomeComponent extends React.Component { : render() { return ( <Text>write some JSX you want</Text> ); } }
change as below.
const SomeComponent = ({ }) => { : return useObserver(() => ( <Text>write some JSX you want</Text> )); };
iii) replace constructor() and lifecycle method( componentWillMount ) to useEffect()
class SomeComponent extends React.Component { : constructor(props) { super(props); // write some initialize code you want } componentWillMount() { // write some code you want } : }
change as below.
import React, { useEffect } from 'react'; : const SomeComponent = ({ aStore, bStore, }) => { : useEffect(() => { // write some initialize code you want }, []); useEffect(() => { // write some code you want }, [aStore, bStore]); : };