Blog>
Snippets

Conditional Rendering with React Hooks

Showcase a client-side component that uses useState and useEffect to render content conditionally based on fetched data.
import React, { useState, useEffect } from 'react';

function ConditionalComponent() {
  // State to store fetched data
  const [data, setData] = useState(null);
  // State to track the loading status
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      try {
        // Replace with your data fetching logic
        const response = await fetch('/my-api-endpoint');
        const result = await response.json();
        setData(result);
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        setLoading(false);
      }
    }

    // Invoke the fetchData function
    fetchData();
  }, []); // The empty array means the effect runs only once after initial render

  // Render different components based on the state
  return (
    <div>
      {loading ? (
        <p>Loading...</p>
      ) : data ? (
        <div>
          {/* Render the data here */}
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      ) : (
        <p>No data found</p>
      )}
    </div>
  );
}

export default ConditionalComponent;
This JavaScript code represents a React functional component utilizing hooks to conditionally render UI based on fetched data. Initially, it uses useState to establish 'data' and 'loading' state variables. useEffect is then employed to fetch data from a specified endpoint on component mount. The component will render a loading message while fetching data, then render the fetched data upon successful acquisition, or display a message if no data is found. Make sure to replace '/my-api-endpoint' with your actual data source.