Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use componentWillMount() in React Hooks?

In the official docs of React it mentions -

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

My question is - how can we use the componentWillMount() lifecyle method in a hook?

like image 254
Abrar Avatar asked Nov 25 '18 04:11

Abrar


People also ask

How do you write componentWillMount in React hooks?

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.

Can we mimic componentWillMount () using React hooks?

You cannot use any of the existing React lifecycle methods like ComponentDidMount, ComponentWillUnmount, etc. in a hook based component.

Why we use componentWillMount in React?

The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle.


2 Answers

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', () => {})   } }, []) 
like image 121
Bhaskar Gyan Vardhan Avatar answered Sep 21 '22 18:09

Bhaskar Gyan Vardhan


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.

like image 28
Ben Carp Avatar answered Sep 19 '22 18:09

Ben Carp