drcmda / react-contextual

🚀 react-contextual is a small (less than 1KB) helper around React 16s new context api

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

cause memory leak when used in SSR

hardfist opened this issue · 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.

commented

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

@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 jayphelps/react-observable-subscribe#1

commented

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