Skip to content

react 18 changes - getting registerStateContainer from context #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

63 changes: 38 additions & 25 deletions src/ContainerRoot/ContainerRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,12 @@ import React, { PropsWithChildren, useEffect, useRef, useState } from "react";
import {
Action,
getUniqueId,
registerStateContainer,
registerStateContainer as libRegisterStateContainer,
unregisterStateContainer,
} from "key-value-state-container";

import { ContainerRootContext } from "./context";
import { ContainerRootProps } from "./props";
import { reRegister } from "./re-register";

export const ContainerRoot = <TState extends Object, TAction extends Action>(
props: PropsWithChildren<ContainerRootProps<TState, TAction>>
Expand All @@ -48,10 +47,9 @@ export const ContainerRoot = <TState extends Object, TAction extends Action>(
persistence,
reducer,
} = props;
const runningFirstTimeRef = useRef<boolean>(true);
if (runningFirstTimeRef.current) {
runningFirstTimeRef.current = false;
registerStateContainer({

const registerStateContainer = () => {
libRegisterStateContainer({
autoActions,
autoState,
config,
Expand All @@ -60,36 +58,51 @@ export const ContainerRoot = <TState extends Object, TAction extends Action>(
persistence,
reducer,
});
}
};

useEffect(() => {
const runningFirstTimeRef = useRef<boolean>(true);
if (runningFirstTimeRef.current) {
runningFirstTimeRef.current = false;
/**
* Checking for unregistered container
* Container might be unregistered due to `useEffect` return function
* called twice in React 18 Strict Mode
* We need to register the container here, with the first render.
*
* Assuming the `console.log()` invocations are printed out for
* mount/unmount component lifecycle events (by `useEffect()`),
* the printout for React 18 Strict Mode would look as follows:
*
* useSelector mounted ⭐️
* ContainerRoot mounted ⭐️⭐️
* useSelector unmounted
* ContainerRoot unmounted
* useSelector mounted ⭐️⭐️⭐️
* ContainerRoot mounted
*
* Please note is is way too late to register the container in the ⭐️⭐️
* (as there was a `useSelector` call in ⭐️, that wanted to register
* callback listeners with an unregistered container!)
*
* The same story goes with `useSelector`, marked by ⭐️⭐️⭐️,
* that needs a container to be registered.
*
* Keep in mind the biggest possible memory issues for a container
* are the callback listeners mentioned above,
* as these can easily allocate GBs of memory
* (btw. this problem is handled by the `useSelector` code)
*/
if (reRegister({ containerId })) {
registerStateContainer({
autoActions,
autoState,
config,
containerId,
initialState,
persistence,
reducer,
});
}
registerStateContainer();
}

useEffect(() => {
return () => {
unregisterStateContainer({
containerId,
});
unregisterStateContainer({ containerId });
};
}, []);

return (
<ContainerRootContext.Provider
value={{
containerId,
registerStateContainer,
}}
>
{children}
Expand Down
2 changes: 2 additions & 0 deletions src/ContainerRoot/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@ import { getUniqueId } from "key-value-state-container";

export interface ContainerRootContextProps {
containerId: string;
registerStateContainer: () => void;
}

export const ContainerRootContext = React.createContext<
ContainerRootContextProps
>({
containerId: getUniqueId(),
registerStateContainer: () => { },
});
16 changes: 0 additions & 16 deletions src/ContainerRoot/re-register.ts

This file was deleted.

41 changes: 41 additions & 0 deletions src/use-get-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
The MIT License (MIT)

Copyright Tomasz Szatkowski and WealthArc https://www.wealtharc.com (c) 2023

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import { useContext } from "react";

import {
ContainerRootContext,
ContainerRootContextProps,
} from "./ContainerRoot/context";

type Result = {
containerIdFromContext: string;
registerStateContainer: () => void;
}

export const useGetContext = (): Result => {
const { containerId, registerStateContainer } =
useContext<ContainerRootContextProps>(ContainerRootContext);
return { containerIdFromContext: containerId, registerStateContainer };
};
31 changes: 25 additions & 6 deletions src/use-selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import { useEffect, useRef, useState } from "react";
import {
Action,
ClientNotificationCallbackArgs,
containerRegistered,
getContainer,
getUniqueId,
registerStateChangedCallback,
TKnownStatePath,
unregisterStateChangedCallback,
} from "key-value-state-container";
import { useGetContainerId } from "./use-get-container-id";
import { RendersWithContainerId } from "./types/contracts";
import { useGetContext } from "./use-get-context";

interface Args<TState extends Object, TAction extends Action = Action>
extends Partial<RendersWithContainerId> {
Expand Down Expand Up @@ -67,8 +68,8 @@ export const useSelector = <
`${listenerTag ? `${listenerTag}:` : ""}${getUniqueId()}`
);
const unmountedRef = useRef<boolean>(false);
const containerFromHook = useGetContainerId();
const containerId = containerIdFromProps || containerFromHook;
const { containerIdFromContext, registerStateContainer } = useGetContext();
const containerId = containerIdFromProps || containerIdFromContext;
const initialState =
getContainer<TState>({
containerId,
Expand All @@ -78,15 +79,24 @@ export const useSelector = <
const lateInvoke =
typeof lateInvokeFromProps === "boolean" ? lateInvokeFromProps : true;
const [currentState, setCurrentState] = useState(initialState);

useEffect(() => {
return () => {
unmountedRef.current = true;
};
/**
* Component gets mounted
*/
unmountedRef.current = false;
}, []);

useEffect(() => {
if (switchOff) {
return;
}
/**
* Awkward, but necessary logic, explained in ContextRoot.tsx component.
*/
if (!containerRegistered({ containerId })) {
registerStateContainer();
}
const statePaths =
typeof statePath === "string"
? [statePath]
Expand Down Expand Up @@ -138,5 +148,14 @@ export const useSelector = <
};
}, [setCurrentState]);

useEffect(() => {
return () => {
/**
* component gets unmounted
*/
unmountedRef.current = true;
};
}, []);

return currentState;
};