how to add dependency array to a component did mount in react class component

421 Views Asked by At

hi i am using react class component and would want to know that is it possible to create a dependency array for component Did Mount, like in use Effect

1

There are 1 best solutions below

0
On

As per React Docs,

  1. If you need to run some logic everytime the component re-renders (state change or prop change) - use the componentDidUpdate method (React Docs). This emulates the same behaviour as useEffect(someCallback)
  2. If you need to reset some state whenever a props changes - use the key prop. Everytime the key changes, react will create a new component, and as per component lifecycle, the logic inside the constructor will run again. (It's not necessary for the key to be used in Array.map) Check out this url
  3. Lifecycle methods like componentDidMount will help emulate the same behaviour as useEffect(someCallback, [])

Reference - React Docs - getDerivedStateFromProps

useEffect also allows us to set a cleanup function for clearing timers and whatnot. These activities can be done inside the componentWillUnmount method (React Docs)