Step 6

This section has nothing to do with React Hooks!

Notice the services/api.js file contains the API_KEY. Given the code repository is public, the entire universe will see our API_KEY. In the case of this app, this is not that big a deal! However, generally, you don't want to expose API keys or other potentially sensitive information in the source code.

Here is one strategy to hide the API key.

  1. Create .env file in the root of the project (not inside the src folder)
  2. Set environment variables starting with REACT_APP_
  3. Access the variable by process.env.REACT_APP_... in components
  4. Add .env to your .gitignore file to not push it to the GitHub repository

For example, I created a .env file with the following content:

REACT_APP_API_KEY="your-api-key-goes-here"

And, updated services/api.js file:

  const BASE_URL = "https://zenquotes.io/api";
- const API_KEY = "your-api-key-goes-here";
+ const API_KEY = process.env.REACT_APP_API_KEY;

I have updated .gitignore to exclude .env file from the repository.

If you run the app locally, it will work as before. However, if you visit the GitHub repository, you will not find a .env file in the repository!

Moreover, there is no API key inside the services/api.js!