Search code examples
javascriptreactjsuse-state

How can I update a setState from a parent using a child?


I'm learning React and trying to understand the concept of props and useState Hook working together.

My goal was to make a simple counter and I started with the increase function of it, but I'm getting anywhere.

App.js

import Increase from "./components/Increase";
import { useState } from "react";
import "./App.css";

function App() {
  const [count, setCount] = useState("0");

  return (
    <div>a
      <p>Counter</p>
      <p>{count}</p>
      <Increase onIncrease={(count) => setCount(count)} />
    </div>
  );
}

export default App;

Increase.js

const Increase = (props) => {
  const increaseHandler = (setCount) => {
    setCount((props.count = props.count + 1));
  };

  return <button onClick={increaseHandler}>+</button>;
};

export default Increase;

Solution

  • Here is your solution just added increase handler in parent file (App.js) because parent can manage counter state.

    App.js

    import Increase from "./components/Increase";
    import { useState } from "react";
    import "./App.css";
    
    export default function App() {
      const [count, setCount] = useState(0);
      const increaseHandler = () => {
        setCount(count + 1);
      };
      return (
        <div>
          a<p>Counter</p>
          <p>{count}</p>
          <Increase onIncrease={increaseHandler} />
        </div>
      );
    }
    

    Increase.js

    const Increase = (props) => {
      const { onIncrease } = props;
      return <button onClick={() => onIncrease()}>+</button>;
    };
    
    export default Increase;