Skip to content
Advertisement

Why the useEffect hook does not work with state variable in context?

My code is here.

I expect the content of the array testingData should be shown.

However, it does not be shown.

When I remove the useEffect hook, it works.

Would you tell me why and how can I fix it?

Advertisement

Answer

In react, a component only renders if there are any state or prop changes. In your codebase rowList is a variable instead of a state. if you convert it to state, it should work.

import React, { useContext, useEffect, useState } from "react";
import WebContext from "./WebContext";
export default function QQTableBody(props) {
  let { testingData, setTestingData } = useContext(WebContext);
  const [rowList, setRowList] = useState([]);
  // let rowList=[];
  useEffect(() => {
    const list = [];
    testingData.forEach(data => {
      list.push(
        <tr>
         <td>{data}</td>
        </tr>
     );
   });
    setRowList(list);
   }, [testingData]);
 
   return <tbody>{rowList}</tbody>;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement