score:686

Accepted answer

you cannot use any of the existing lifecycle methods (componentdidmount, componentdidupdate, componentwillunmount etc.) in a hook. they can only be used in class components. and with hooks you can only use in functional components. the line below comes from the react doc:

if you’re familiar with react class lifecycle methods, you can think of useeffect hook as componentdidmount, componentdidupdate, and componentwillunmount combined.

suggest is, you can mimic these lifecycle method from class component in a functional components.

code inside componentdidmount run once when the component is mounted. useeffect hook equivalent for this behaviour is

useeffect(() => {
  // your code here
}, []);

notice the second parameter here (empty array). this will run only once.

without the second parameter the useeffect hook will be called on every render of the component which can be dangerous.

useeffect(() => {
  // your code here
});

componentwillunmount is use for cleanup (like removing event listeners, cancel the timer etc). say you are adding a event listener in componentdidmount and removing it in componentwillunmount as below.

componentdidmount() {
  window.addeventlistener('mousemove', () => {})
}

componentwillunmount() {
  window.removeeventlistener('mousemove', () => {})
}

hook equivalent of above code will be as follows

useeffect(() => {
  window.addeventlistener('mousemove', () => {});

  // returned function will be called on component unmount 
  return () => {
    window.removeeventlistener('mousemove', () => {})
  }
}, [])

score:-5

just simply add an empty dependenncy array in useeffect it will works as componentdidmount.

useeffect(() => {
  // your code here
  console.log("componentdidmount")
}, []);

score:-1

react component is a function right? so just let componentwillmount moment be the function body before return statement.

function componentwillmountmomentishere() {
  console.log('component will mount')
}


function anycomponent(){
  const [greeting, setgreeting] = usestate('hello')

  componentwillmountmomentishere()

  
  return <h1>{greeting}</h1>
}

score:0

https://reactjs.org/docs/hooks-reference.html#usememo

remember that the function passed to usememo runs during rendering. don’t do anything there that you wouldn’t normally do while rendering. for example, side effects belong in useeffect, not usememo.

score:0

ben carp's answer seems like only valid one to me.

but since we are using functional ways just another approach can be benefiting from closure and hoc:

const injectwillmount = function(node, willmountcallback) {
  let iscalled = true;
  return function() {
    if (iscalled) {
      willmountcallback();
      iscalled = false;
    }
    return node;
  };
};

then use it :

const yournewcomponent = injectwillmount(<yourcomponent />, () => {
  console.log("your pre-mount logic here");
});

score:0

short answer to your original question, how componentwillmount can be used with react hooks:

componentwillmount is deprecated and considered legacy. react recommendation:

generally, we recommend using the constructor() instead for initializing state.

now in the hook faq you find out, what the equivalent of a class constructor for function components is:

constructor: function components don’t need a constructor. you can initialize the state in the usestate call. if computing the initial state is expensive, you can pass a function to usestate.

so a usage example of componentwillmount looks like this:

const mycomp = () => {
  const [state, setstate] = usestate(42) // set initial value directly in usestate 
  const [state2, setstate2] = usestate(createinitval) // call complex computation

  return <div>{state},{state2}</div>
};

const createinitval = () => { /* ... complex computation or other logic */ return 42; };

score:0

it might be clear for most, but have in mind that a function called inside the function component's body, acts as a beforerender. this doesn't answer the question of running code on componentwillmount (before the first render) but since it is related and might help others i'm leaving it here.

const mycomponent = () => {
  const [counter, setcounter] = usestate(0)
  
  useeffect(() => {
    console.log('after render')
  })

  const iterate = () => {
    setcounter(prevcounter => prevcounter+1)
  }

  const beforerender = () => {
    console.log('before render')
  }

  beforerender()

  return (
    <div>
      <div>{counter}</div>
      <button onclick={iterate}>re-render</button>
    </div>
  )
}

export default mycomponent

score:0

as it has been stated in react document:

you might be thinking that we’d need a separate effect to perform the cleanup. but code for adding and removing a subscription is so tightly related that useeffect is designed to keep it together. if your effect returns a function, react will run it when it is time to clean up:

useeffect(() => {
    function handlestatuschange(status) {
      setisonline(status.isonline);
    }
    chatapi.subscribetofriendstatus(props.friend.id, handlestatuschange);
    // specify how to clean up after this effect:
    return function cleanup() {
      chatapi.unsubscribefromfriendstatus(props.friend.id, handlestatuschange);
    };
  });

  if (isonline === null) {
    return 'loading...';
  }
  return isonline ? 'online' : 'offline';
}

so the only thing that we need to have the componentwillunmount in hooks is to return a function inside a useeffect, as explained above.

score:0

so for react hooks, i think declaring your logic before the return statement can work. you should have a state that is set to true by default. in my case, i called the state componentwillmount. then a conditional to run a block of code when this state is true (the block of code contains the logic you want executed in your componentwillmount), the last statement in this block should be resetting the componentwillmountstate to false (this step is important because if it is not done, infinite rendering will occur) example

// do your imports here

const app = () =>  {
  useeffect(() => {
    console.log('component did mount')
  }, [])
  const [count, setcount] = usestate(0);
  const [componentwillmount, setcomponentwillmount] = usestate(true);
  if (componentwillmount) {
    console.log('component will mount')
    // the logic you want in the componentwillmount lifecycle
    setcomponentwillmount(false)
  }
  
  return (
    <div>
      <div>
      <button onclick={() => setcount(count + 1)}> 
        press me
      </button>
      <p>
        {count}
      </p>
      
      </div>
    </div>
  )
}

score:0

this might not be the exact alternative to the componentwillmount method but here is a method that can be used to achieve the same objective but by using useeffect :

first initialize the object where you retrive the data to an empty value and define the useeffect method:

const [details, setdetails] = usestate("")

  useeffect(() => {
    retrievedata(); 
  }, []);

const retrievedata = () => {       
       getdata()                  // get data from the server 
      .then(response => {
        console.log(response.data);
        setdetails(response.data)
      })
      .catch(e => {
        console.log(e);
      })
  }

now in the jsx where we return add a terenary operator

*return(
  <div>
    { 
   details ? (
   <div class="">
   <p>add your jsx here</p>
</div>
): (
  <div>
<h4>content is still loading.....</h4>
</div>
)
}
  </div>
)*

this will ensure that until the object 'details' has data in it the second part of the terenary operator is loaded which inturn triggers the useeffect method that leads to setting the data received from the server in the 'details' object, hence the rendering of the primary jsx

score:0

simple place a dependency array within react.useeffect() as the second argument. if any of the dependencies update, the hook will cause a side effect that will run and ultimately update your component.

score:0

we recently had problem with this because we need to do something when a component will mount, that is we need to update the global state.

so i created this hook, not sure how good of an approach this is but so far it works as long as we use this sparingly and only for simple tasks. i probably would not use this for network requests and other long-running and complex tasks.

import { useref } from 'react';

function usecomponentwillmount(callback: () => void) {
  const hasmounted = useref(false);

  if (!hasmounted.current) {
    (() => {
      hasmounted.current = true;
      callback();
    })();
  }

  console.log(hasmounted.current);
  return null;
}

export default usecomponentwillmount;

score:1

there is a nice workaround to implement componentdidmount and componentwillunmount with useeffect.

based on the documentation, useeffect can return a "cleanup" function. this function will not be invoked on the first useeffect call, only on subsequent calls.

therefore, if we use the useeffect hook with no dependencies at all, the hook will be called only when the component is mounted and the "cleanup" function is called when the component is unmounted.

useeffect(() => {
    console.log('componentdidmount');

    return () => {
        console.log('componentwillunmount');
    };
}, []);

the cleanup return function call is invoked only when the component is unmounted.

hope this helps.

score:2

given that

  • componentwillmount is deprecated (1, 2, 3), and that the suggested replacement is executing code in the constructor
  • code executed before the return statement of a functional component is implicitly run before rendering it
  • the rough equivalent of mounting a class component is the initial call of a functional component
  • the goal is to execute some code once, before the ui is updated

the solution would be

running a function in the body of the functional component only once. this can be achieved with usestate, usememo, or useeffect, depending on the timing required for the use case.

since the code needs to run before the initial render is committed to the screen, this disqualifies useeffect, as “the function passed to useeffect will run after the render is committed to the screen.” 4.

since we want to guarantee that the code will only run once, this disqualifies usememo, as "in the future, react may choose to “forget” some previously memoized values and recalculate them on next render" 5.

usestate supports lazy initial state calculations that are guaranteed to only run once during the initial render, which seems like a good candidate for the job.

example with usestate:

const runoncebeforerender = () => {};

const component = () => {
  usestate(runoncebeforerender);

  return (<></>);
}

as a custom hook:

const runoncebeforerender = () => {};

const useoninitialrender = (fn) => {
  usestate(fn);
}

const component = () => {
  useoninitialrender(runoncebeforerender);

  return (<></>);
};

the runoncebeforerender function can optionally return a state that will be available immediately upon the first render of the function, triggering no re-renders.

a (probably unnecessary) npm package: useonce hook

score:7

i wrote a custom hook that will run a function once before first render.

usebeforefirstrender.js

import { usestate, useeffect } from 'react'

export default (fun) => {
  const [hasrendered, sethasrendered] = usestate(false)

  useeffect(() => sethasrendered(true), [hasrendered])

  if (!hasrendered) {
    fun()
  }
}

usage:

import react, { useeffect } from 'react'
import usebeforefirstrender from '../hooks/usebeforefirstrender'


export default () => { 
  usebeforefirstrender(() => {
    console.log('do stuff here')
  })

  return (
    <div>
      my component
    </div>
  )
}

score:17

this is the way how i simulate constructor in functional components using the useref hook:

function component(props) {
    const willmount = useref(true);
    if (willmount.current) {
        console.log('this runs only once before rendering the component.');
        willmount.current = false;        
    }

    return (<h1>meow world!</h1>);
}

here is the lifecycle example:

function renderlog(props) {
    console.log('render log: ' + props.children);
    return (<>{props.children}</>);
}

function component(props) {

    console.log('body');
    const [count, setcount] = usestate(0);
    const willmount = useref(true);

    if (willmount.current) {
        console.log('first time load (it runs only once)');
        setcount(2);
        willmount.current = false;
    } else {
        console.log('repeated load');
    }

    useeffect(() => {
        console.log('component did mount (it runs only once)');
        return () => console.log('component will unmount');
    }, []);

    useeffect(() => {
        console.log('component did update');
    });

    useeffect(() => {
        console.log('component will receive props');
    }, [count]);


    return (
        <>
        <h1>{count}</h1>
        <renderlog>{count}</renderlog>
        </>
    );
}
[log] body
[log] first time load (it runs only once)
[log] body
[log] repeated load
[log] render log: 2
[log] component did mount (it runs only once)
[log] component did update
[log] component will receive props

of course class components don't have body steps, it's not possible to make 1:1 simulation due to different concepts of functions and classes.

score:19

uselayouteffect could accomplish this with an empty set of observers ([]) if the functionality is actually similar to componentwillmount -- it will run before the first content gets to the dom -- though there are actually two updates but they are synchronous before drawing to the screen.

for example:


function mycomponent({ ...anditsprops }) {
     uselayouteffect(()=> {
          console.log('i am about to render!');
     },[]);

     return (<div>some content</div>);
}

the benefit over usestate with an initializer/setter or useeffect is though it may compute a render pass, there are no actual re-renders to the dom that a user will notice, and it is run before the first noticable render, which is not the case for useeffect. the downside is of course a slight delay in your first render since a check/update has to happen before painting to screen. it really does depend on your use-case, though.

i think personally, usememo is fine in some niche cases where you need to do something heavy -- as long as you keep in mind it is the exception vs the norm.

score:23

react lifecycle methods in hooks

for simple visual reference follow this image

enter image description here

as you can simply see in the above picture that for componentwillunmount, you have to do like this

 useeffect(() => {
    return () => {
        console.log('componentwillunmount');
    };
   }, []);

score:24

you can hack the usememo hook to imitate a componentwillmount lifecycle event. just do:

const component = () => {
   usememo(() => {
     // componentwillmount events
   },[]);
   useeffect(() => {
     // componentdidmount events
     return () => {
       // componentwillunmount events
     }
   }, []);
};

you would need to keep the usememo hook before anything that interacts with your state. this is not how it is intended but it worked for me for all componentwillmount issues.

this works because usememo doesnt require to actually return a value and you dont have to actually use it as anything, but since it memorizes a value based on dependencies which will only run once ("[]") and its on top of our component it runs once when the component mounts before anything else.

score:70

according to reactjs.org, componentwillmount will not be supported in the future. https://reactjs.org/docs/react-component.html#unsafe_componentwillmount

there is no need to use componentwillmount.

if you want to do something before the component mounted, just do it in the constructor().

if you want to do network requests, do not do it in componentwillmount. it is because doing this will lead to unexpected bugs.

network requests can be done in componentdidmount.

hope it helps.


updated on 08/03/2019

the reason why you ask for componentwillmount is probably because you want to initialize the state before renders.

just do it in usestate.

const helloworld=()=>{
    const [value,setvalue]=usestate(0) //initialize your state here
    return <p>{value}</p>
}
export default helloworld;

or maybe you want to run a function in componentwillmount, for example, if your original code looks like this:

componentwillmount(){
  console.log('componentwillmount')
}

with hook, all you need to do is to remove the lifecycle method:

const hookcomponent=()=>{
    console.log('componentwillmount')
    return <p>you have transfered componewillmount from class component into hook </p>
}

i just want to add something to the first answer about useeffect.

useeffect(()=>{})

useeffect runs on every render, it is a combination of componentdidupdate, componentdidmount and componentwillunmount.

 useeffect(()=>{},[])

if we add an empty array in useeffect it runs just when the component mounted. it is because useeffect will compare the array you passed to it. so it does not have to be an empty array.it can be array that is not changing. for example, it can be [1,2,3] or ['1,2']. useeffect still only runs when component mounted.

it depends on you whether you want it to run just once or runs after every render. it is not dangerous if you forgot to add an array as long as you know what you are doing.

i created a sample for hook. please check it out.

https://codesandbox.io/s/kw6xj153wr


updated on 21/08/2019

it has been a while since i wrote the above answer. there is something that i think you need to pay attention to. when you use

useeffect(()=>{},[])

when react compares the values you passed to the array [], it uses object.is() to compare. if you pass an object to it, such as

useeffect(()=>{},[{name:'tom'}])

this is exactly the same as:

useeffect(()=>{})

it will re-render every time because when object.is() compares an object, it compares its reference, not the value itself. it is the same as why {}==={} returns false because their references are different. if you still want to compare the object itself not the reference, you can do something like this:

useeffect(()=>{},[json.stringify({name:'tom'})])

update on 7/09/2021:

a few updates about the dependency:

generally speaking, if you use a function or an object as a dependency, it will always re-render. but react already provides you with the solution: usecallback and usememo

usecallback is able to memorize a function. usememo is able to memorize an object.

see this article:

https://javascript.plainenglish.io/5-useeffect-infinite-loop-patterns-2dc9d45a253f

score:207

usecomponentwillmount hook

const usecomponentwillmount = (cb) => {
    const willmount = useref(true)

    if (willmount.current) cb()

    willmount.current = false
}

this hook could be a saver when there is an issue of sequence (such as running before another script). if that isn't the case, use usecomnponentdidmount which is more aligned with react hooks paradigm.

usecomponentdidmount hook

const usecomponentdidmount = cb => useeffect(cb, []);

if you know your effect should only run once at the beginning use this solution. it will run only once after component has mounted.

useeffect paradigm

class components have lifecycle methods which are defined as points in the timeline of the component. hooks don't follow this paradigm. instead effects should be structured by their content.

function post({postid}){
  const [post, setpost] = usestate({})

  useeffect(()=>{
    fetchposts(postid).then(
      (postobject) => setpost(postobject)
    )
  }, [postid])

  ...
}

in the example above the effect deals with fetching the content of a post. instead of a certain point in time it has a value it is dependent on - postid. every time postid gets a new value (including initialization) it will rerun.

component will mount discussion

in class components componentwillmount is considered legacy (source 1, source2). it's legacy since it might run more than once, and there is an alternative - using the constructor. those considerations aren't relevant for a functional component.


Related Query

More Query from same tag