Skip to content

React Hooks – Updating state using props without event handlers

I’m relatively new to React and this is what I’m trying to accomplish:

  1. User selects an item from the sidebar.
  2. The elementID is lifted up to the parent(app.js).
  3. app.js sends it to its child, Graphs.
  4. 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.

 - Sidebar
 - Title-bar
 - Graphs
function Graphs(props) {
  const [graphs, addGraphs] = useState([]);
  useEffect(() => {
    if (props.graphID) {
  }, [props.graphID]);
  return (

Thank you!


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 [
  }, [id]);
  return (
  , index) => {
                <p key={index}>