'How to pass react useState hook from parent to Child components

I am trying to pass a React hook setter to the Child component where the state is to be updated.

    export default () => {
        const [fromDate, setFromDate] = useState(null);
        const [toDate, setToDate] = useState(null);
    }

return html`<div className="cal">
                        <${Calendar} config=${config} setFromDate=${setFromDate} setToDate=${setToDate}/>
                    </div>
                `;

And trying to access it in Child component like this:

export default ({ config, setFromDate, setToDate }) => {
    useEffect(() => {
        fromDate = setFromDate('01/01/2022');
        console.log('!!!!!!!!!!!!@@@@@@@@@', fromDate);
        toDate = setToDate('03/02/2022');
        console.log('@@@@@@@@@@@@', toDate);
        initCalendar();
    }, [config, setFromDate, setToDate]);
}

But the console comes as undefined. How do I proceed?



Solution 1:[1]

You also need to pass fromDate and toDate as props.

return html`<div className="cal">
    <${Calendar} 
        config=${config} 
        setFromDate=${setFromDate} 
        setToDate=${setToDate}
        fromDate=${fromDate}
        toDate=${toDate}
    />
</div>`;

and

export default ({ fromDate, toDate, config, setFromDate, setToDate }) => {
    useEffect(() => {
        setFromDate('01/01/2022');
        setToDate('03/02/2022');

        console.log('INSIDE OF useEffect toDate', toDate);
        console.log('INSIDE OF useEffect fromDate', fromDate);
        // IMPORTANT! THIS CONSOLE.LOGs will NOT log the changes
        // recently made to toDate and fromDate
        // call it outside useEffect

        initCalendar();
    }, [config, fromDate, toDate]);

    console.log('OUTSIDE OF useEffect toDate', toDate);
    console.log('OUTSIDE OF useEffect fromDate', fromDate);
    // NOW THIS CONSOLE.LOGs WILL log the changes
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tenshi