useEffect for the MySQL connection, establish and fetch the data from database

useEffect for the MySQL connection, establish and fetch the data from database

To connect to MySQL and get data in a React component, you need to use an async operation, usually in the useEffect hook. You'll need a MySQL library for Node.js, like mysql2, to manage the async connection and data fetching. Also, think about using the state to save the data you get.

Here's an example using mysql2 and the useEffect hook:

import React, { useState, useEffect } from 'react';
import mysql from 'mysql2/promise';

const MyComponent = () => {
  // State to store the fetched data
  const [data, setData] = useState(null);

  // State to handle loading and error states
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // MySQL connection configuration
  const dbConfig = {
    host: 'your-mysql-host',
    user: 'your-mysql-username',
    password: 'your-mysql-password',
    database: 'your-database-name',

  useEffect(() => {
    // Function to establish MySQL connection and fetch data
    const fetchDataFromMySQL = async () => {
      try {
        // Set loading state to true while establishing connection and fetching data

        // Create a MySQL connection
        const connection = await mysql.createConnection(dbConfig);

        // Execute a query to fetch data
        const [rows] = await connection.query('SELECT * FROM your_table_name');

        // Close the connection
        await connection.end();

        // Set the data state with the fetched data

        // Set loading state to false after successfully fetching data

      } catch (error) {

        // If an error occurs during the fetch, set the error state

        // Set loading state to false


    // Call the fetchDataFromMySQL function when the component mounts
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // The empty dependency array means this effect will only run once, similar to componentDidMount

  // Render the component based on the loading and error states
  if (loading) {
    return <p>Loading...</p>;

  if (error) {
    return <p>Error: {error.message}</p>;

  // Render the component with the fetched data
  return (
        { => (
          <li key={}>{}</li>

export default MyComponent;

In this example,

  1. The mysql2 library is used to establish a MySQL connection and execute a query to fetch data.

  2. The useEffect hook is used to initiate the MySQL connection and data fetching when the component mounts (similar to componentDidMount in class components).

  3. The fetchDataFromMySQL function is a simple async function that manages the MySQL connection, runs a query, and updates the state depending on whether the fetch succeeds or fails.

  4. The component renders differently based on the loading and error states, and if the data is successfully fetched, it renders the component with the fetched data.

Make sure to replace the placeholder values in dbConfig with your actual MySQL connection details. Also, change 'your_table_name' to the name of the table you want to use.