title: ReactJS: how to call useEffect hook only once to fetch API data
body: <p>Using React, I have the following functional component where I make use of <code>useEffect()</code>:</p>
  
  <pre><code>import React, { useEffect } from 'react';
  import { connect } from 'react-redux';
  
  const MessagingComponent = React.memo(({ loadMessages, messages, ...props }) =&gt; {
  
    useEffect(() =&gt; {
      loadMessages();
    });
  
    return &lt;div {...props}&gt;These are the messages&lt;/div&gt;;
  });
  
  const mapDispatchToProps = dispatch =&gt; ({
    loadMessages: () =&gt; dispatch({ type: 'LOAD_MESSAGES' })
  });
  
  const mapStateToProps = state =&gt; {
    return {
      messages: state.chatt.messages.chatMessages
    };
  };
  
  export default connect(
    mapStateToProps,
    mapDispatchToProps
  )(MessagingComponent);
  </code></pre>
  
  <p>As you can see, I have an effect callback that calls the <code>loadMessages()</code> function in the <code>useEffect()</code> callback in my <code>MessagingComponent</code>:</p>
  
  <pre><code>  useEffect(() =&gt; {
      loadMessages();
    });
  </code></pre>
  
  <p>The call to <code>loadMessages()</code> loads messages which causes the component to re-render.  This behaviour is as expected, however the problem is that the re-render causes the <code>useEffect()</code> hook to fire again, which causes <code>loadMessages()</code> to be called again. This in turn loads the messages from the back-end and causes the component to render again, and the cycle repeats. </p>
  
  <p>How can I avoid this? Should I simply put an if condition in the <code>useEffect()</code> hook, and check for the messages property?</p>