'context is not behaving properly in react. printing default values
I created below context in react.
NameContext.tsx
import { createContext } from 'react';
export const AppContext = createContext("NA");
I used this context inside my Layout.tsx . I am using inside Layout because I have some business logic to execute. based on that isActive value will be set.
const [isActive,setIsActive]=useState("NO");
return(
<AppContext.Provider value={isActive}>
<User/>
</AppContext.Provider>
)
now under User.tsx I am accessing this tab.
import { useContext } from "react";
import { Link } from "react-router-dom"
import { AppContext } from "../context/NameContext";
const User = ()=>{
const context = useContext(AppContext);
let isActive:any;
if(context=="YES")
isActive=true;
else
isActive=false;
console.log("context is:"+context);
console.log(isActive);
return(
<>
<span>
{isActive && <Link to="user" > List of Users</Link> }
</span>
</>
)
}
export default User;
in just one page refresh it is delivering values many times and most of the time default values. I dont want default values but the value which I set in provider. how can I avoid this abnormal behaviour.
Solution 1:[1]
create a wrapper then put the Layout inside the Wrapper component, the value will be available globally.
//Wrapper
import React, { useState } from "react";
export const Context = React.createContext();
const Wrapper = (props) => {
const [active, setActive] = useState('NO');
function changeValue(value) {
setActive(value)
}
function getCurrent() {
return active;
}
return (
<Context.Provider value={{ active, changeValue, getCurrent }}>
{props.children}
</Context.Provider>
);
};
export default Wrapper;
// index.tsx
import Wrapper from './path/Wrapper'
<Wrapper>
<App />
</Wrapper>
//Layout must be inside App!
//Layout.tsx
import { Context } from "../../layout/Wrapper";
export default function Layout(){
const context = useContext(Context);
console.log(context.getCurrent()) // NO
context.changeValue('YES')
console.log(context.getCurrent()) // YES
}
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 | Paiman Rasoli |

