'How to mange the re-rendering of components through the app

I'm fairly new to React and I'm not sure how to handle components refresh through my app. See the below example:

  • I have a component <ChartPage> which contains 2 components <ChartDataList> and <Chart>
  • The component <Chart> contains a <ReactECharts>
  • When I uncheck the checkbox on a <ChartDataList> I would like to update the chart's options to provoke a re-render of the chart.

What is the best way to handle a case like this?

enter image description here



Solution 1:[1]

while the solution you came up with might work - it isn't very efficient and could cause you problems down the road.

Managing State in React

useState

Like @Disco mentioned, if you have a state that is shared among multiple child components - you should store the state in the parent. Take a look at this for more details: https://reactjs.org/docs/lifting-state-up.html

As an example, you could have something like:

const [selectedGraphs, setSelectedGraphs] = useState([]);

Where selectedGraphs would be a list of graph id's. Then you could pass these 2 variables to you ChartDataList.js as well as Chart.js. Don't forget however to listen to a change in props via the useEffect hook.

Context

If you find yourself working with highly nested data (like ChartPage => Chart => ReactECharts) it might be useful to use the useContext hook. Click here to learn more: https://reactjs.org/docs/hooks-reference.html#usecontext

Managing State in Redux

If you find yourself struggling with how state management works in react, you can try out redux which is ussaly much simpler.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Inbar Koursh