score:1

import React, { useContext, useState} from 'react';

const CounterContext = React.createContext({
    counter: 0
});

const MainComponent  = (props) => {
    const [counter, setCounter] = useState(0);
    
    const updateCounter = () => {
        setCounter(counter + 1);
    }

    return <CounterContext.Provider value={
        counter,
        update: updateCounter
    }>
        <div>
            <Child1 />
            <Child2 />
        </div>
    </CounterContext.Provider>;
}


const Child1 = (props) => {
    const counter = useContext(CounterContext);
    return <div>This is the counter value {counter.counter}</div>
}

const Child2 = (props) => {
    const counter = useContext(CounterContext);

    return <div>
        <h2>Here the button to update the counter</h2>
        <button onClick={counter.update}>
            Update counter state in the parent
        </button>
    </div>
}

Related Query

More Query from same tag