In this Code Sandbox, I have a provider that initializes and passes context to App
const appContext = {
person: "Larry"
};
render(
<BrowserRouter>
<AppContext.Provider value={appContext}>
<App />
</AppContext.Provider>
</BrowserRouter>,
document.getElementById("root")
);
And there's a consumer under App that modifies context depending on its state. It does this so when a user clicks into a different link and comes back, the state (in this case, the selected dropdown) can be restored from context.
const Consumer = props => {
const [dropdownOpen, setOpen] = useState(false);
const appContext = useContext(AppContext);
const toggle = () => setOpen(!dropdownOpen);
const changePerson = e => {
appContext.person = e.currentTarget.textContent;
};
const people = ["Moe", "Larry", "Curly"];
return (
<ButtonDropdown isOpen={dropdownOpen} toggle={toggle}>
<DropdownToggle caret>{appContext.person}</DropdownToggle>
<DropdownMenu>
{people.map((p, idx) => {
return (
<DropdownItem
key={idx}
active={appContext.person === p}
onClick={changePerson}
>
{p}
</DropdownItem>
);
})}
</DropdownMenu>
</ButtonDropdown>
);
};
Is it safe to directly update appContext.person in the consumer as shown above? The code runs fine, but I just want to make sure it's ok to do this.