Published on

How to Use ComponentWillMount with React Hooks

Authors

React hooks provide an alternative to componentDidMount, componentDidUpdate and componentWillUnmount as described in the official docs:

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

But no mention is made of how to handle componentWillMount in the hooks docs. Searching Google, Github and StackOverflow did not return any decent answers.

It turns out that componentWillMount is being deprecated as per here. The main reason for this is because you normally put stuff in here if you say want to synchronously get something from the server to use in your render method. This means that some of the options you have are to:

  • Show a loader while getting your data then render the UI that depends on it.
  • Hit the render method twice: once when you first render (without the server data) and again when you get the server data.
  • Load portions of the UI that do not depend on the data and avoid rendering the parts that do until the data is available. This can be done simply by using the short circuit syntax. For example, if I need myAwesomeData which comes from the server I would do something like:
class MyAmazingComponent extends React.Component {
...
    componentWillMount() {
        const data = getDataFromServer():
        this.setState({myAwesomeData: data});
    }
...
    render() {
        return (
            <>
            <h1>Hello</h1>
            {!_.isEmpty(this.state.myAwesomeData) &&
                <MyComponent data={this.state.myAwesomeData}/>
            }
            </>
        );
    }
}

Once this life cycle method has been fully deprecated, the suspense API will be available as an alternative. This API will render only once server data has been received and only once.

In the meantime I used a similar approach to the above but using React hooks alternatives:

const MyAwesomeComponent = () => {
    const [myAwesomeData, setMyAwesomeData] = useState(null) ;
...
    useEffect(() => {
        const fetchData = async () => {
            const data = await getDataFromServer();
             setMyAwesomeData(data);
        };
    }, []);

...
    return (
        <>
            <h1>Hello</h1>
            {!_.isEmpty(myAwesomeData) &&
                <MyComponent data={myAwesomeData}/>
            }
        </>
    );
}