react-contextual icon indicating copy to clipboard operation
react-contextual copied to clipboard

cause memory leak when used in SSR

Open hardfist opened this issue 7 years ago • 3 comments

store.js

  componentWillUnmount() {
        if (this.props.id) removeNamedContext(this.props.id)
}

namedContext.js

    componentWillUnmount() {
                removeNamedContext(this.name)
 }

context.js

const createContext = React.createContext
const providers = new Map()
const ProviderContext = createContext()

export function createNamedContext(name, initialState) {
    const context = createContext(initialState)
    providers.set(name, context)
    return context
}

export function getNamedContext(name) {
    return providers.get(name)
}

export function removeNamedContext(name) {
    providers.delete(name)
}

componentWillUnmount will not execute on server side, which cause providers increase rapidly with request increase and cause memory leak.

hardfist avatar Apr 09 '18 09:04 hardfist

@hardfist are there any best practices regarding this? If componentWillUnmount doesn't fire, where would you normally free local state?

drcmda avatar Apr 09 '18 10:04 drcmda

@drcmda normally you call createNamedContext in componentDidMount and call removeNamedContext in compoentWillUnmount,but if you really need use createNamedContext in constructor, your can free local state in componentWillMont on server side using environment detecting just like this https://github.com/jayphelps/react-observable-subscribe/issues/1

hardfist avatar Apr 10 '18 01:04 hardfist

Great, thanks a lot, i will take a look after a nap. : )

drcmda avatar Apr 10 '18 01:04 drcmda