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
grapharray.
Is there a better way than this? P.S I’ll have more than 1x useEffect in this component.
App.js
- Sidebar
- Title-bar
- Graphs
function Graphs(props) {
const [graphs, addGraphs] = useState([]);
useEffect(() => {
if (props.graphID) {
addGraphs(graphs.concat(props.graphID));
}
}, [props.graphID]);
return (
<div>{graphs}</div>
);
}
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:
import React from "react";
function MyComponent({id}) {
const [list, setList] = React.useState([]);
React.useEffect(() => {
if (id) {
setList(previousState => {
return [
...previousState,
id
];
});
}
}, [id]);
return (
<div>
{
list.map((_id, index) => {
<p key={index}>
{_id.toString()}
</p>
)
}
</div>
);
}