Search code examples
javascriptreactjsrenderingreact-hooks

Avoid calling effect inside component when conditionally rendering


I've got the following component:

const Component = () => {
  useEffect(() => {
    console.log('Component useEffect')
  }, [])

  return <Text>element</Text>
}

When I conditionally render the component above, the side effect gets called every time the component is re-attached:

{someCondition && <Component />}

Is there a way to avoid this by memoizing the rendered element somehow? Is this due to the nature of hooks being sensitive to ordering...?


Solution

  • Either perform the effect inside your parent component or move the conditional render logic inside child component

    const Parent = () =>{
        return <Child condition={false} />
    }
    
    const Child = ({ condition }) =>{
        useEffect(() =>{},[])
    
        return condition ? <span /> : null 
    }