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 ?
@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