Re-render a child component (React with Hooks)

Viewed 6926

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

3 Answers

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

<Graph ... key={newKey} />

You do not need to force a render of your component, you just need to call setDatas() with some new data. Once you do that, it will rerender Graph with the new data. Make sure you are calling setDatas() with a new array, not just an updated version of the existing datas array, it needs to be a new object reference

At the minute, you are only calling it once, on mount, using the useEffect hook (with no dependencies, denoted by the empty dependency array)

you missed the return value on the hook. Please see this implementation.

Hook (updateGraph.js)

const UpdateGraph = () => {

    const [data, setData] = useState([]);

    const fetchData = async () => {
        setData([
            { 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(() => {
        fetchData();
    }, []);

    return [data];

};

export { UpdateGraph };

Implementation (my-component.js)

const { UpdateGraph } from "./UpdateGraph.js" // your path...

const [datas] = UpdateGraph();

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