Reputation: 72
Hello everyone,
First post on StackOverflow, and quite new to the world of Web Dev but I am working with a friend of mine to guide me. I came here because none of us seems to find the answer about an issue that I have. So here it is, hoping that I'll make myself clear enough for you to help me.
So, I am in the process of creating my first website for a friend, it is a simple project. Where I am trying to render (and re-render) components through a context (and different changes of said context). So here is a reduced version of my project for the purpose of this question https://codesandbox.io/s/mystifying-https-l5c6d?file=/src/App.js
For the context, I am trying to display an infobox (yellow square) corresponding to a planet (gray circles) everytime we click on the said planet and it should disappear everytime we click on an other planet to make an other infobox appear.
So for this purpose I created a context with a state containing objects representing the planets and the onClick function on each planets does the job of changing a boolean which render or not the infobox.
As seen with the console.log it does change, but it actually never re-render the components planets with the infobox on click whereas if you manually change the context it wil appear on first render. Since I see everywhere (react docs, and stackoverflow) that : "a component calling useContext will always re-render when the context value changes."
Why is mine not re-rendering on change ?
Hoping I have made myself clear and gave enough informations.
edit : sorry to everyone, I think I have updated my sandbox, first time using it and got confused by my local storage I guess.
Upvotes: 1
Views: 527
Reputation: 2966
Your sandbox code is showing empty, though the issue may be because you aren't storing your context value within your app component's state. If you change a static value, a re-render won't be triggered.
See this working example: https://codesandbox.io/s/eager-fermat-6ji6y?file=/src/App.js
Edit: Your reducer was mutating state directly, change to below and it works
export const planetReducer = (planetsTab, action) => {
switch (action.type) {
case "switchPlanetToggle":
return [
...planetsTab.slice(0, action.index),
{
...planetsTab[action.index],
planetToggle: !planetsTab[action.index].planetToggle
},
...planetsTab.slice(action.index + 1)
];
default:
return planetsTab;
}
};
https://codesandbox.io/s/twilight-sea-lwwep?file=/src/PlanetsContext.js
Upvotes: 1