Skip to content
Advertisement

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.

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>
  );
}
Advertisement