I have a React application with a CompanyContext and CompanyProvider. This allows a user to change the current company in the UI (like Slack) and the current company ID will be available to all components in the app.
The new ID is available to all components, but I want each component to reset the state of each component with its default. I mainly want to reset the state of status
so data loading, etc. occurs for the current company.
Here’s what I’m doing now in each component using this changed company…
const {getCurrentCompanyId} = useCompany();
const [status, setStatus] = useState<PageStatus>(PageStatus.IsLoading);
const [localCompanyId, setLocalCompanyId] = useState<string>('');
const companyId = getCurrentCompanyId();
useEffect(() => {
// The company changed.
if (companyId != localCompanyId) {
setStatus(PageStatus.IsLoading);
setLocalCompanyId(companyId);
}
// Ready to load the current company.
if (companyId == localCompanyId) {
// TODO: Reload data here.
setStatus(PageStatus.IsReady);
}
}, [companyId, localCompanyId]);
If the component detects that the global and “local” company ID do not match, the status
is set back to IsLoading
then I can reload the necessary data. I would need to do this on each top-level component/route.
The React docs showed setting a key
for a child component, but not sure how this would work for top-level components directly under Outlet.
Is there a better way to do this? It seems a bit hacky.
1
You can leverage the key
prop at a higher level to force a remount
of components when the company changes, which is a cleaner and more scalable solution than manually resetting the state in each component.
ex:
const App = () => {
const { getCurrentCompanyId } = useCompany();
const companyId = getCurrentCompanyId();
return (
<div>
<Outlet key={companyId} />
</div>
);
};
2