Flagsmith / react-navigation-focus-render

Wrapping components in this will ensure that they are only rendered when the screen is focused
13 stars 1 forks source link

Hook and React.memo Version #1

Open 2sem opened 2 years ago

2sem commented 2 years ago

Thanks for your awesome library. My project can't use react-navigation 5. so I cloned your source as hook version. I don't know yet how create this with useMemo instead of React.memo. How about this?

import React, { ReactElement } from 'react'
import { useIsFocused } from 'react-navigation-hooks'

type RendererProps = Props & {
  isFocused: boolean
}

type IRenderer = React.FC<RendererProps>

const Renderer: IRenderer = ({ children, Wrapper }) => {
  return Wrapper ? <Wrapper>{children}</Wrapper> : (children as ReactElement)
}

const MemorizedRender = React.memo(Renderer, (_, { isFocused }) => {
  return !isFocused
})

export const FocusRender: IFocusRender = ({ children, Wrapper }) => {
  const isFocused = useIsFocused()

  return (
    <MemorizedRender isFocused={isFocused} Wrapper={Wrapper}>
      {children}
    </MemorizedRender>
  )
}
pors commented 1 year ago

Cool!

@2sem BTW How is this related to react-navigation 5? I'm using version 6, but screens at the bottom of the stack still get re-rendered without FocusRender.

2sem commented 1 year ago

Cool!

@2sem BTW How is this related to react-navigation 5? I'm using version 6, but screens at the bottom of the stack still get re-rendered without FocusRender.

I forgot :), I guess it was related by useIsFocused. Now my project's navigation has been upgrade to 6. so useIsFocused is imported from @react-native/native.

pors commented 1 year ago

Cool! @2sem BTW How is this related to react-navigation 5? I'm using version 6, but screens at the bottom of the stack still get re-rendered without FocusRender.

I forgot :), I guess it was related by useIsFocused. Now my project's navigation has been upgrade to 6. so useIsFocused is imported from @react-native/native.

Ah OK! I thought that v5 might have something like this built in as an option.