Search code examples
javascriptreactjsuse-effect

If useEffect is not called, do something else React.js


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.


Solution

  • 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