useState setValue for boolean is not working on calling from different component

68 Views Asked by At

I'm trying to update boolean usestate variable value in first component based on some method call completion in second component. But usestate boolean value doesnt seem to get update in first component.

Below is my sample code

function Component2(props){

cosnt{handle}=props

function handle(){
locate();
}

return(
call handle function above
)

export default Component2
}


function Component1(props){

const[show,SetShow]=useState(false)

function locate(){
setShow(!show)
}

return(
call compoent2
<Component2 handle={handle}>
)

export default Component1

can you please assist why simple setstate for boolean variable not working in component1 on calling from component2. it always remain false. On placing debugger it is confirmed method being called from component2 and call has reached completed in component1, still boolean value remain false.

1

There are 1 best solutions below

1
kungfuKenny On
function Component2(props) {
    const { handle } = props;

    function handleClick() {
        // Call the function passed from Component1
        handle();
    }

    return (
        <button onClick={handleClick}>Click me</button>
    );
}

export default Component2;

function Component1() {
    const [show, setShow] = useState(false);

    // Define a function to toggle the state
    function toggleShow() {
        setShow(!show);
    }

    return (
        <div>
            <h1>Component1</h1>
            <p>Show: {show.toString()}</p>
            {/* Pass the toggleShow function as a prop */}
            <Component2 handle={toggleShow} />
        </div>
    );
}

export default Component1;

In this modified version:

  • toggleShow function is defined in Component1, which updates the state of show using setShow.
  • toggleShow is passed down to Component2 as a prop named handle.
  • When the button in Component2 is clicked, it calls the handle function, which ultimately triggers the toggleShow function in Component1, thus updating the state accordingly.

This way, when the function passed from Component1 to Component2 is called, it updates the state of Component1, and the component re-renders with the updated state.