Blog>
Snippets

Accessing Browser Environment Variables in useEffect Hook

Demonstrate the use of environment variables on the client side within the useEffect hook in a functional component.
import React, { useState, useEffect } from 'react';

function ExampleComponent() {
  // State to store the environment variable value
  const [envValue, setEnvValue] = useState('');

  useEffect(() => {
    // Simulate accessing an environment variable (e.g., REACT_APP_API_URL)
    // Note: Environment variables must be prefixed with REACT_APP_ in CRA
    const apiUrl = process.env.REACT_APP_API_URL;

    // Update the state with the environment variable
    setEnvValue(apiUrl);

    // Optional: Do something with the API URL, like fetching data
    // fetch(apiUrl).then(...);
  }, []); // Only run once on component mount

  return (
    <div>
      <p>API URL from environment variable: {envUrl}</p>
    </div>
  );
}

export default ExampleComponent;
This code defines a function component that uses the useEffect hook to access a browser environment variable (e.g., REACT_APP_API_URL). It sets this environment variable to a state variable (envValue) when the component mounts, and then renders it to display.