Unable to understand the React context (asynchronous)

Hi I’ve created context in the react globally. This is the value of the context => {price:22}

and When I’m trying to increment the context.price by click of the button. It gets incremented after clicking the button for the second time and so on.

I’ve added the context.price as the dependency to useEffect hook. useEffect detects the update but in the UI it won’t re-render. May be I’m doing something wrong please correct me.

Here is my code…

import React, {useContext, createContext, useState, useEffect} from "react";

const reactContext = React.createContext({
    hey:"this is new one",
    price:22
})


function Robo(){
    const context = useContext(reactContext);
    let [price, setPrice] = useState(context.price);
    const contextFunction = async function (){
             setPrice(prevPrice=>prevPrice+1);
            context.price = price; // Here I'm trying to update the context.price
    }

    useEffect(()=>{
        console.log(context.price, price); // 22,23 
    },[context.price]); // Though I've added context.price as dependency it notices the update but it doesn't render in UI and console logs the old state i.e, 22
    return (
        <>
        <button onClick={contextFunction}>click the button</button>
        <div>
            {context.price} {/* 22 on UI */}
        </div>
        </>
    )
}

function Fiction(){

    const context = useContext(reactContext);

    return(
        <>
        <Robo/>
        <div>
            <p>this is the price {context.price}</p> {/*Here I want to render the context.price. It is different component but how do i wrap the component please explain */}
        </div>

        </>
    )
}

export default Fiction;

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.