title: Dynamically load images before render
body: <p>I've browsed a lot of questions but I can't find a correct answer to this. Say I have an <code>images</code> folder, and I want to display a specific image in there. I don't know the name of the image to be displayed, it's returned by a RESTful API along with many other details on that object I'm displaying.</p>
  
  <p>I considered a few alternatives to do that:</p>
  
  <ul>
  <li>Load all images no matter what, then only render the ones I need. I found this in a few places, but I think it's pretty heavy, isn't it?</li>
  <li>Use <code>webpack</code> to <code>require</code> the file I need on the fly.</li>
  </ul>
  
  <p>The second option seems to be the best here. However, when I do:</p>
  
  <pre><code>componentDidMount() {
      axios.get('http://url.to/my/RESTful/api')
         .then(res =&gt; {
             this.setState(res.data);
         });
  }
  render() {
      var pic = require(`../images/${this.state.picture}`)
      return (&lt;img src={pic} alt="some name" /&gt;)
  );
  </code></pre>
  
  <p>React complains it can't load <code>undefined</code>, because it starts rendering before the axios call gets done. Another alternative is thus to display a loader while the call is being done, or preventing rendering in general. But my question is rather: what's the best practice here? Should I have a loader on every page loading dynamic data? I suppose I'm missing something, which is why I'm reaching out. How do you usually do that? Thanks a lot.</p>