In my react code, inside a component, I am fetching a value from session storage(inside useEffect hook). When console printed, it shows the value. But inside the render(or return method), it does not have the value just fetched. Is there a delay while fetching from session storage?
Circumvented the problem after storing the same in state and fetching inside render!
let myValue = '';
useEffect(()=>{
myValue = sessionStorage.getItem("someKey");
},[]);
// In the return method
return {
<div>{myValue}</div>
}
Why does value fetched from session storage not available immediately in render?
The issue here is that you're expecting a variable value change to trigger a re-render. React doesn't work this way and you'll need another approach if you want to change a value and have it re-render:
Consider:
const [myValue, setMyValue] = useState('');
useEffect(()=>{
setMyValue(sessionStorage.getItem("someKey"));
},[]);
// In the return method
return {
<div>{myValue}</div>
}