drcmda / react-contextual

🚀 react-contextual is a small (less than 1KB) helper around React 16s new context api
MIT License
642 stars 23 forks source link

cause memory leak when used in SSR #18

Open hardfist opened 6 years ago

hardfist commented 6 years ago

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.

drcmda commented 6 years ago

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

hardfist commented 6 years ago

@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

drcmda commented 6 years ago

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