I’m relatively new to React and this is what I’m trying to accomplish:
- User selects an item from the sidebar.
- The elementID is lifted up to the parent(app.js).
- app.js sends it to its child, Graphs.
- Graphs will create a Graph component and append to its
graph
array.
Is there a better way than this? P.S I’ll have more than 1x useEffect
in this component.
JavaScript
x
19
19
1
App.js
2
- Sidebar
3
- Title-bar
4
- Graphs
5
6
function Graphs(props) {
7
const [graphs, addGraphs] = useState([]);
8
9
useEffect(() => {
10
if (props.graphID) {
11
addGraphs(graphs.concat(props.graphID));
12
}
13
}, [props.graphID]);
14
15
return (
16
<div>{graphs}</div>
17
);
18
}
19
Thank you!
Advertisement
Answer
I believe it is a good approach, but you should use an functional state update. The “setter” functions of React.useState
hook has a callback with previous state, so you shall update it like this:
JavaScript
1
29
29
1
import React from "react";
2
3
function MyComponent({id}) {
4
const [list, setList] = React.useState([]);
5
6
React.useEffect(() => {
7
if (id) {
8
setList(previousState => {
9
return [
10
previousState,
11
id
12
];
13
});
14
}
15
}, [id]);
16
17
return (
18
<div>
19
{
20
list.map((_id, index) => {
21
<p key={index}>
22
{_id.toString()}
23
</p>
24
)
25
}
26
</div>
27
);
28
}
29