How to call loading function with React useEffect only once

The useEffect React hook will run the passed in function on every change. This can be optimized to let it call only when the desired properties change.

What if I want to call an initialization function from componentDidMount and not call it again on changes? Let’s say I want to load an entity, but the loading function doesn’t need any data from the component. How can we make this using the useEffect hook?

class MyComponent extends React.PureComponent {
    componentDidMount() {
        loadDataOnlyOnce();
    }
    render() { ... }
}

With hooks this could look like this:

function MyComponent() {
    useEffect(() => {
        loadDataOnlyOnce(); // this will fire on every change :(
    }, [...???]);
    return (...);
}

11 Answers
11

Leave a Comment