Home > Back-end >  React hooks updating parent state through child and rerendering
React hooks updating parent state through child and rerendering

Time:10-13

I have components that are dependent on the parent state. When I pass in the parent useState hook to the child, the component does not seem to render.

on my ChildA component, I call a function to perform props.updateFiles(). ChildB has nothing rendered even after the prop has changed.

const Parent = () => {
    const [files, setFiles] = useState([]);

    return (
      <div>
        <ChildA files={files} updateFiles={setFiles} />
        <ChildB files={files} updateFiles={setFiles} />
      </div>
    );
  };
export default Parent;
const ChildA = (props) => {
  const appendFile = () => {
    let old = props.files;
    old.push({ name: "asdf" });
    props.updateFiles(old);
  };

  return (
    <div >
        <button onClick={appendFile}>append file</button>
    </div>
  );
};
export default ChildA;

const ChildB = (props) => {

  const renderProps = (items) => {
    let out = items.map(({ name }, index) => <div>{name}</div>);
    return out;
  };

  return (
    <div>
      {renderProps(props.files)}
    </div>
  );
};
export default ChildB;

CodePudding user response:

Looks like you're not utilizing the useState hook correctly when it comes to adding an item to an array. You'll need to utilize the ... spread operator. Try changing your code to something like this:

const appendFile = () => {
   let old = props.files;
   props.updateFiles([...old, "asdf"]);
};

Also, when utilizing some events such as mousemove, you'll need to use the callback version:

const appendFile = () => {
   props.updateFiles(oldArray => [...oldArray, "asdf"]);
};
  • Related