Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React change UseState from Child Component

Is it possible to change the value from a useState from inside the child component?

Parent:

const [state, setState] = useState(false);

return <Child func={() => setState(true)}/>

Child:

return <Button onClick={props.func}> Click me to set the state </Button>

It doesn't work this way, is there any way it could work? Thank you

like image 689
tiimo Avatar asked Mar 04 '26 05:03

tiimo


2 Answers

You can do something like this

//PARENT
export default function Parent({}) {
  const [state, setState] = useState(false);
        function setParentValue(value){
             setState(value)
       }

        return <Child setValue={setParentValue} />

}

//CHILD
export default function Child({setValue}) {
  function buttonHandler(){
      setValue('value')
 }
  return <Button onClick={buttonHandler}> Click me to set the state </Button>

}


like image 176
Udendu Abasili Avatar answered Mar 05 '26 17:03

Udendu Abasili


That should work, as long as you also provide a way to look at the changed stateful value:

const { useState } = React;
const App = () => {
  const [state, setState] = useState(false);
  return (
    <div>
      State: {String(state)}
      <Child func={() => setState(true)}/>
    </div>
  );
};
const Child = (props) => {
  return <button onClick={props.func}> Click me to set the state </button>;
};

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
like image 28
CertainPerformance Avatar answered Mar 05 '26 18:03

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!