You are currently viewing How to represent class lifecycle methods with hooks in React or React Native?

How to represent class lifecycle methods with hooks in React or React Native?

In React, you can represent the call lifecycle methods using the following hooks:

  1. useEffect(): This hook can be used to represent the componentDidMount(), componentDidUpdate(), and componentWillUnmount() methods. You can pass a function to useEffect() as its first argument, which will be executed after every render cycle. You can also pass a second argument to useEffect(), which is an array of dependencies that, when changed, will trigger the function to be re-executed.
  2. useLayoutEffect(): This hook is similar to useEffect(), but it runs synchronously after all DOM mutations are applied. It can be used to represent the componentDidMount() and componentDidUpdate() methods, but not componentWillUnmount().
  3. useMemo(): This hook can be used to represent the shouldComponentUpdate() method. You can pass a function and an array of dependencies to useMemo(), and it will only recompute the value of the function when the dependencies change.
  4. useCallback(): This hook is similar to useMemo(), but it returns a memoized callback function instead of a memoized value. It can be used to represent event handlers that are passed down to child components.
  5. useRef(): This hook can be used to represent the componentDidMount() and componentDidUpdate() methods. You can create a ref using useRef() and assign it to an element in your component’s render method. The ref will persist across re-renders and can be used to access the element’s properties and methods.
import React, { useState, useEffect, useLayoutEffect, useMemo, useCallback, useRef } from 'react';

function MyComponent(props) {

  const [count, setCount] = useState(0);
  const myRef = useRef(null);
  const inputRef = useRef(null);

  // componentDidMount and componentDidUpdate
  useEffect(() => {
    console.log('Component has mounted or updated');
    console.log('useEffect: componentDidMount or componentDidUpdate');
    return () => {
      console.log('Component will unmount');
      console.log('useEffect: componentWillUnmount');
    };
  }, [count]);

  // componentDidMount only
  useLayoutEffect(() => {
    console.log('Component has mounted');
    console.log('useLayoutEffect: componentDidMount only');
  }, []);

  // shouldComponentUpdate
  const expensiveCalculation = useMemo(() => {
    console.log('Expensive calculation');
    return count * 2;
  }, [count]);

  // componentWillUnmount
  useEffect(() => {
    return () => {
      console.log('useEffect: componentWillUnmount');
    };
  }, []);

  // event handler
  const handleClick = useCallback(() => {
    console.log('Button clicked');
    setCount(count + 1);
  }, [count]);
  
  // memoized value
  const memoizedValue = useMemo(() => {
    console.log('useMemo: computing memoized value');
    return count * 2;
  }, [count]);

  // memoized callback
  const memoizedCallback = useCallback(() => {
    console.log('useCallback: memoized callback invoked');
  }, []);

  // focus input on mount
  useEffect(() => {
    inputRef.current.focus();
  }, []);

  // render
  return (
    <div ref={myRef}>
      <p>Count: {count}</p>
      <p>Expensive Calculation: {expensiveCalculation}</p>
      <button onClick={handleClick}>Increment</button>
      <p>Memoized Value: {memoizedValue}</p>
      <input type="text" value={text} onChange={(e) => setText(e.target.value)} ref={inputRef} />
      <button onClick={memoizedCallback}>Invoke Memoized Callback</button>
    </div>
  );
}
export default MyComponent;

In this example, we’re using:

  • useState to manage state in our component.
  • useEffect to represent componentDidMount and componentDidUpdate.
  • useLayoutEffect to represent componentDidMount only.
  • useMemo to memoize a computed value.
  • useCallback to memoize a callback function.
  • useRef to get a reference to a div element.

In the useEffect hook, we’re logging into the console to show when the component mounts, updates, and unmounts. We’re also returning a function that will be called when the component is unmounting.

In the useLayoutEffect hook, we’re logging into the console to show when the component mounts.

In the useMemo hook, we’re computing a memoized value based on the count state variable. This is similar to shouldComponentUpdate because we’re only re-computing the expensive calculation when count changes.

In the useCallback hook, we’re creating a memoized callback function that logs to the console when it’s invoked. This is similar to shouldComponentUpdate because we’re only creating a new function when count changes.

Finally, in the useRef hook, we’re getting a reference to a div  and Input element.

crackdetudo.com

Leave a Reply