Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-render a child component (React with Hooks)

I have a parent component called "Causes", and a child component called "Graph",

There's a hook called "datas", that is created and updated in "Causes" (parent), and I pass it as props to "Graph" (child).

The first time, everything works, but when I update "datas" in "Causes" (parent), "Graph" (child) still has the old "datas" array of objects.

How can I force the re-render of the child component ?

const [datas, setDatas] = useState([
    { shop: "00h-8h", value: 250, color: "#A2AAC2" },
    { shop: "8h-12h", value: 420, color: "#A2AAC2" },
    { shop: "12h-16h", value: 500, color: "#A2AAC2" },
    { shop: "16h-20h", value: 80, color: "#A2AAC2" },
    { shop: "20h-00h", value: 80, color: "#A2AAC2" }
]);

useEffect(() => {
  setDatas(newArray); <- this updates data, but the component below always got the old datas
}, []);


return (
  <Graph
                  h={400}
                  w={900}
                  data={datas}
                  defaultKeys={["shop", "value"]}
  />
)

Code available here : https://pastebin.com/aLzsz8md

like image 879
VersifiXion Avatar asked Feb 21 '26 14:02

VersifiXion


1 Answers

You can solve this problem by adding a key to the Graph component.

<Graph ... key={newKey} />
like image 160
Osman Safak Avatar answered Feb 23 '26 02:02

Osman Safak