0

and couldn't find the answer on the internet. Is there a way to do something if an useEffect is called and do something else if useEffect is not called. Like an if statement?

like:

**if** (useEffect(() => {
   },[hello]) {
call a function } **else** {
call another function}

The goal is to call a function if the var hello changes and call another one is hello doesn't change. Thank you.

Simon
  • 209
  • 4
  • 12

3 Answers3

1

you can achieve that if you call useEffect on every render and by creating a couple of custom hooks to check the previous values of your state-props.

const Component = (props) => {
  const hasHelloChanged = useHasChanged(hello);

  useEffect(() => {
    if (hasHelloChanged) {
      // your code if hello has changed
    } else {
     // your code if it hasn't
    }
  });

  return <>...</>;
};

const useHasChanged= (value) => {
    const prevValue = usePrevious(value);

    return prevValue !== value;
}

const usePrevious = (value) => {
    const ref = useRef();
    useEffect(() => {
      ref.current = value;
    });
    return ref.current;
}

You can take a look on this thread for more

SakisTsalk
  • 796
  • 7
  • 18
  • Thank you! I've managed to do what I want with your post. But I don't know why sometimes I get a "Rendered more hooks than during the previous render" when I refresh the browser. – Simon Jun 29 '21 at 10:11
  • are you using another hook inside your useEffect? – SakisTsalk Jun 29 '21 at 10:23
  • I'm just using a hook for changing the state init ' useEffect(() => { if (hasCountryLabelChanged) { if(matchingOption) { changeSelectedPathway(matchingOption) } else { changeSelectedPathway(options[0]) } } else { changeSelectedPathway(optionSelected) } },[hasCountryLabelChanged, matchingOption, optionSelected])' – Simon Jun 29 '21 at 11:29
  • if `changeSelectedPathway` is a setState hook, you should add it in your dependency array as well. – SakisTsalk Jun 29 '21 at 11:30
1

You can't do exactly what you outlined because React hooks like useEffect cannot be called conditionally.

As the other poster said, your best bet is to call useEffect on each render and trigger branching actions from inside useEffect.

terraforme
  • 448
  • 4
  • 5
1

Have you tried using two different useEffect calls, one when hello changes and the the other whenever the other property in question changes. for example;

useEffect(() => { // desired action }), [hello]);

The above effect will always be called whenever the value of hello changes, while;

    useEffect(() => {
// desired action
}), [theOtherPropertyInQuestion]);

will always be called whenever the value of theOtherPropertyInQuestion changes and if they are not mutually exclusive, you can use

    useEffect(() => {
// desired action
}), [hello, theOtherPropertyInQuestion]);
alfrednoble
  • 91
  • 1
  • 5