Skip to content

Instantly share code, notes, and snippets.

@halitbatur
Created June 22, 2021 14:26
Show Gist options
  • Save halitbatur/032fa1617591ba10e892b13075199544 to your computer and use it in GitHub Desktop.
Save halitbatur/032fa1617591ba10e892b13075199544 to your computer and use it in GitHub Desktop.
useEffect discussion
  1. When does a React component re-render?
  2. What does the React.useMemo hook do?
  3. How can you replicate componentWillUnmount using useEffect ?
  4. How can you replicate componentDidUpdate using useEffect ?
@ARS-coding
Copy link

1) Props and state can make components re-render.
2) useMemo is a React hook that memorizes the output of a function.
3) The useEffect function takes two arguments: a didUpdate function, and an array of dependencies. The didUpdate function can optionally return a cleanUp function.
4) The useEffect function takes two arguments: a didUpdate function, and an array of dependencies. The didUpdate function can optionally return a cleanUp function.

@awadbilal
Copy link

Members: Bilal Avvad && Abduallah Barmu && Derya

  1. React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.

  2. useMemo is a React hook that memorizes the output of a function. That is it. useMemo accepts two arguments: a function and a list of dependencies. useMemo will call the function and return its return value. Then, every time you call useMemo again, it will first check if any dependencies have changed. If not, it will return the cached return value, not calling the function. If they have changed, useMemo will call the provided function again and repeat the process.

  3. To do the cleanup after the component unmounts, we have a simple way to perform the equivalent of the componentWillUnmount using the useEffect Hook.
    The only thing that we need to do is to return a function inside the callback function of the useEffect Hook, like this:

useEffect(() => {
  window.addEventListener("mousemove", () => {});
  return () => {
    window.removeEventListener("mousemove", () => {})
  }
}, []);

That’s it. It’s very simple, we can use the useEffect Hook to perform side effects similar to the lifecycle methods that we have in class components, and with clean and straightforward code.

  1. To perform the equivalent of the componentDidUpdate using the useEffect Hook, we should do this:
useEffect(() => {
  // Inside this callback function we perform our side effects.
}, [dependency]);

That’s it. In here, we’re passing our array of dependencies as the second parameter, and inside that array, we should pass the dependency that we want to watch. If you don’t pass any dependency, the useEffect Hook will still work as the componentDidUpdate lifecycle method.

@udenizdemirbilek
Copy link

Group: Abdulrahman, Deniz, Nur
1)When does a React component re-render?
React components automatically re-render whenever there is a change in their state or props.
2)What does the React.useMemo hook do?
Returns a memoized value.
Pass a “create” function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies has changed.
3)How can you replicate componentWillUnmount using useEffect ?
when we want to remove a component from our DOM, in React this is called unmounting.
We have just one lifecycle method for that lifecycle stage called componentWillUnmount. This lifecycle method will be invoked when the component is about to be removed from the DOM:
componentWillUnmount() {
console.log("Component unmounted!");
}
The function passed to useEffect may return a clean-up function

useEffect(() => {
const subscription = props.source.subscribe();
return () => {
// Clean up the subscription
subscription.unsubscribe();
};
});

4)How can you replicate componentDidUpdate using useEffect ?
We want to update only if the source prop has changed. To implement this, pass a second argument to useEffect that is the array of values that the effect depends on

useEffect(
() => {
const subscription = props.source.subscribe();
return () => {
subscription.unsubscribe();
};
},
[props.source],
);

The useRef creates an "instance variable" in functional component. It acts as a flag to indicate whether it is in mount or update phase without updating state.

const mounted = useRef();
useEffect(() => {
if (!mounted.current) {
// do componentDidMount logic
mounted.current = true;
} else {
// do componentDidUpdate logic
}
});

@MoulhamHallak
Copy link

Our group: Buse Şentürk, Moulham Hallak, Yeşim Nur Akar

  1. it renders automatically when there is a change in its state/prop

  2. it remembers a complex function. it memorizes the output of a function so that you won't have to re-render. should be used when there is a high amount of data. useMemo calls the func & returns its value and everytime you call it it will check whether there is a change in the dependencies. If not, returns the saved value without recalling the function again (bc its value is already memorized and still the same) but if changed, will call the func and repeat the process.

  3. useEffect = (componentDidMount , componentDidUpdate and componentWillUnmount class lifecycle). We can combine this life cycle method using useEffect & we can set up listeners, fetch data from API and remove listeners before comp is removed from DOM.

componentWillUnmount is used for “cleanup”: it removes event listeners, cancels timers etc.

componentWillUnmount() {
console.log('Hello World');

}

// with useEffect()
useEffect(() => {
func () //let’s say
console.log('Hello World');
return () => {
// you can call another func that disconnects the func with database
console.log('Do some cleanup');
}
}, [ ])

  1. componentDidUpdate is invoked immediately after any update. useEffect is like a shortcut for componentDidMount and componentDidUpdate (two birds at a time). takes two arguments: function and initial array (optional).
    // With componentDidUpdate()
    componentDidUpdate(prevProps) {
    console.log(Hello World ${prevProps});
    }
    // with useEffect()
    useEffect(() => {
    console.log('Hello World');
    }, [prevProps])

@mustafaguldag
Copy link

1- React components automatically re-render whenever there is a change in their state or props.

2- useMemo is a hook that memorize the output of a function and it accept 2 arguments.

3- componentWillUnmount() {
console.log('Hello World');
}

// with useEffect()
useEffect(() => {
console.log('Hello World');
return () => {
console.log('Do some cleanup');
}
}, [])

4- useEffect(() => {
console.log('Hello World');
}, [prevProps])

Group Members: Mustafa / Moumen / Isa

@ayse8888
Copy link

Group Room 7 - M. Zakaria Alalaya, Mohammed Manar Yazji, Ayşe Çimen Başar

  1. The react component re-renders automatically whenever a state or a prop changes / gets updated

    • useMemo is a React hook that memorizes the output of a function.
    • In memoization, the result is remembered, when the same exact parameters are passed-in subsequently.
    • If we have a function to execute 1 + 1, it will return 2. But if it uses memoization, the next time we run 1’s through the function it won’t
      add them up, it will just remember the answer is 2 without executing the adding function.
    • useMemo accepts two arguments: a function and a list of dependencies.
      --> const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  2. componentWillUnmount is a life cycle of React that we use in Class Components and is used to perform clean-up for any DOM-elements.
    But with the hooks, we can use life cycle methods in React with function components and we do this with UseEffect
    The replication will be as follows :
    // With componentWillUnmount()
    componentWillUnmount() {
    console.log('Hello World');
    }
    // with useEffect()
    useEffect(() => {
    console.log('Hello World');
    return () => {
    console.log('Do some cleanup');
    }
    }, [])

  3. componentDidUpdate method is invoked immediately after updating occurs.
    When we want our state to change when the component renders, we use this method. And we put our state as our initial value in our UseEffect hook.
    The replication will be as follows:
    // With ccomponentDidUpdate()
    componentDidUpdate(prevProps) {
    console.log(Hello World ${prevProps});
    }
    // with useEffect()
    useEffect(() => {
    console.log('Hello World');
    }, [prevProps])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment