0

I'd like to induce a re-render from another component, avoiding the "triggering component" to re-render.

const App = () => {

    const [isPopUpActive, setIsPopUpActive] = useState(false)

    const popUpOnOff = () => {
        if(isPopUpActive)
            setIsPopUpActive(false)
        else
            setIsPopUpActive(true)
    }

    return (
        <div>
            <SomeComponent
                trigger={popUpOnOff}
            />
            <PopUpComponent
                isActive={isPopUpActive}
            />
        </div>
    )
}

I thought wrapping the SomeComponent with React.memo and changing a prop in the PopUpComponent would do it, but calling the trigger function in the SomeComponent re-renders everything. Is there a way to avoid the first component to re-render?

1 Answer 1

2

The identity of the popUpOnOff function changes on each render, so the memoized component can't do anything.

You will need to memoize that callback instead, making it depend on the data it uses:

const App = () => {
  const [isPopUpActive, setIsPopUpActive] = useState(false);

  const popUpOnOff = useCallback(() => {
    setIsPopUpActive(!isPopUpActive);
  }, [isPopUpActive, setIsPopUpActive]);

  return (
    <div>
      <SomeComponent trigger={popUpOnOff} />
      <PopUpComponent isActive={isPopUpActive} />
    </div>
  );
};

Sign up to request clarification or add additional context in comments.

6 Comments

the next state is calculated based on the current state. You should use an updater function instead of relying on closures
and that's not how useMemo works. Maybe you wanted useCallback?
@marzelin Ah, yeah, good point. (Quoth the docs, though: useCallback(fn, deps) is equivalent to useMemo(() => fn, deps) – I was almost there :) )
this is not working, it doesn't make any difference.
I think the only solution to this is to use a class component and implement a shouldComponentUpdate method.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.