score:452
For the stable version of hooks (React Version 16.8.0+)
For componentDidMount
useEffect(() => {
// Your code here
}, []);
For componentDidUpdate
useEffect(() => {
// Your code here
}, [yourDependency]);
For componentWillUnmount
useEffect(() => {
// componentWillUnmount
return () => {
// Your code here
}
}, [yourDependency]);
So in this situation, you need to pass your dependency into this array. Let's assume you have a state like this
const [count, setCount] = useState(0);
And whenever count increases you want to re-render your function component. Then your useEffect
should look like this
useEffect(() => {
// <div>{count}</div>
}, [count]);
This way whenever your count updates your component will re-render. Hopefully this will help a bit.
score:-2
the exact equivalent hook for componentDidMount() is
useEffect(()=>{},[]);
hope this helpful :)
score:-1
You want to use useEffect()
, which, depending on how you use the function, can act just like componentDidMount().
Eg. you could use a custom loaded
state property which is initially set to false, and switch it to true on render, and only fire the effect when this value changes.
score:0
Info about async functions inside the hook:
Effect callbacks are synchronous to prevent race conditions. Put the async function inside:
useEffect(() => {
async function fetchData() {
// You can await here
const response = await MyAPI.getData(someId);
// ...
}
fetchData();
}, [someId]); // Or [] if effect doesn't need props or state
score:0
useLayoutEffect hook is the best alternative to ComponentDidMount
in React Hooks.
useLayoutEffect
hook executes before Rendering UI and useEffect
hook executes after rendering UI. Use it depend on your needs.
Sample Code:
import { useLayoutEffect, useEffect } from "react";
export default function App() {
useEffect(() => {
console.log("useEffect Statements");
}, []);
useLayoutEffect(() => {
console.log("useLayoutEffect Statements");
}, []);
return (
<div>
<h1>Hello Guys</h1>
</div>
);
}
score:1
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Please visit this official docs. Very easy to understand the latest way.
score:2
ComponentDidMount
useEffect(() => {
//code here
}, []);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
score:4
Although accepted answer works, it is not recommended. When you have more than one state and you use it with useEffect, it will give you warning about adding it to dependency array or not using it at all.
It sometimes causes the problem which might give you unpredictable output. So I suggest that you take a little effort to rewrite your function as class. There are very little changes, and you can have some components as class and some as function. You're not obligated to use only one convention.
Take this for example
function App() {
const [appointments, setAppointments] = useState([]);
const [aptId, setAptId] = useState(1);
useEffect(() => {
fetch('./data.json')
.then(response => response.json())
.then(result => {
const apts = result.map(item => {
item.aptId = aptId;
console.log(aptId);
setAptId(aptId + 1);
return item;
})
setAppointments(apts);
});
}, []);
return(...);
}
and
class App extends Component {
constructor() {
super();
this.state = {
appointments: [],
aptId: 1,
}
}
componentDidMount() {
fetch('./data.json')
.then(response => response.json())
.then(result => {
const apts = result.map(item => {
item.aptId = this.state.aptId;
this.setState({aptId: this.state.aptId + 1});
console.log(this.state.aptId);
return item;
});
this.setState({appointments: apts});
});
}
render(...);
}
This is only for example. so lets not talk about best practices or potential issues with the code. Both of this has same logic but the later only works as expected. You might get componentDidMount functionality with useEffect running for this time, but as your app grows, there are chances that you MAY face some issues. So, rather than rewriting at that phase, it's better to do this at early stage.
Besides, OOP is not that bad, if Procedure-Oriented Programming was enough, we would never have had Object-Oriented Programming. It's painful sometimes, but better (technically. personal issues aside).
score:5
useEffect() hook allows us to achieve the functionality of componentDidMount, componentDidUpdate componentWillUnMount functionalities.
Different syntaxes of useEffect() allows to achieve each of the above methods.
i) componentDidMount
useEffect(() => {
//code here
}, []);
ii) componentDidUpdate
useEffect(() => {
//code here
}, [x,y,z]);
//where x,y,z are state variables on whose update, this method should get triggered
iii) componentDidUnmount
useEffect(() => {
//code here
return function() {
//code to be run during unmount phase
}
}, []);
You can check the official react site for more info. Official React Page on Hooks
score:12
There's no componentDidMount
on functional components, but React Hooks provide a way you can emulate the behavior by using the useEffect
hook.
Pass an empty array as the second argument to useEffect()
to run only the callback on mount only.
Please read the documentation on useEffect
.
function ComponentDidMount() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log('componentDidMount');
}, []);
return (
<div>
<p>componentDidMount: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
ReactDOM.render(
<div>
<ComponentDidMount />
</div>,
document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
score:28
There is no exact equivalent for componentDidMount
in react hooks.
In my experience, react hooks requires a different mindset when developing it and generally speaking you should not compare it to the class methods like componentDidMount
.
With that said, there are ways in which you can use hooks to produce a similar effect to componentDidMount
.
Solution 1:
useEffect(() => {
console.log("I have been mounted")
}, [])
Solution 2:
const num = 5
useEffect(() => {
console.log("I will only run if my deps change: ", num)
}, [num])
Solution 3 (With function):
useEffect(() => {
const someFunc = () => {
console.log("Function being run after/on mount")
}
someFunc()
}, [])
Solution 4 (useCallback):
const msg = "some message"
const myFunc = useCallback(() => {
console.log(msg)
}, [msg])
useEffect(() => {
myFunc()
}, [myFunc])
Solution 5 (Getting creative):
export default function useDidMountHook(callback) {
const didMount = useRef(null)
useEffect(() => {
if (callback && !didMount.current) {
didMount.current = true
callback()
}
})
}
It is worth noting that solution 5 should only really be used if none of the other solutions work for your use case. If you do decide you need solution 5 then I recommend using this pre-made hook use-did-mount.
Source (With more detail): Using componentDidMount in react hooks
Source: stackoverflow.com
Related Query
- React Hooks Error: Hooks can only be called inside the body of a function component
- React Hooks and Component Lifecycle Equivalent
- Function inside functional component in React hooks - Performance
- React hooks function component prevent re-render on state update
- React/React-Hooks: Need to run a function onLoad within React Hooks component
- React 16: Call children's function from parent when using hooks and functional component
- React + Antd + Rollup Component Library "Error: Invalid hook call. Hooks can only be called inside of the body of a function component"
- React Hooks can only be called inside the body of a function component
- React 17.0.1: Invalid hook call. Hooks can only be called inside of the body of a function component
- Receiving error - Hooks can only be called inside of the body of a function component when implementing React Spring basic example
- React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
- Trigger child function from parent component using react hooks
- React Hook "useDispatch" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
- React Hooks must be called in a React function component or a custom React Hook function
- React Hook "useState" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function
- React Hooks Mobx: invalid hook call. Hooks can only be called inside of the body of a function component
- React Hooks - function inside function component passed as prop can't access state
- React expose component function and getting data with ComponentDidMount
- React useHistory: Hooks can only be called inside the body of a function component
- How to test a handle function call with a react functional component with hooks
- Passing function to create new component to child using react hooks
- How to wrap React Hooks dispatch into function outside component
- Formik hooks "useField" throws error stating that the component is not a React function component
- React Redux-Toolkit: Invalid hook call - Hooks can only be called inside of the body of a function component
- React Hooks must be called in a React function component when using React RTK query createApi
- React call from class to functional component. Error: Invalid hook call. Hooks can only be called inside of the body of a function component
- React Hooks: Instantiating state hooks on validation Error: Invalid hook call. Hooks can only be called inside of the body of a function component
- Error with calling React Hooks inside of Function Component
- Time consuming function call in componentDidMount of React component
- React Hooks + Mobx => Invalid hook call. Hooks can only be called inside of the body of a function component
More Query from same tag
- React Native - Super expression must either be null or a function
- Display menu on hover reactjs
- Insert value of an <input> into an object -ReactJS
- Checking authentication in React
- React image upload component
- toggle between multiple button style on click of button in react
- Trying to implement debounce in React Project
- How to search for a specific value in an array of objects
- React form loses focus on update
- How to use CSS Modules with webpack in React isomorphic app?
- How can I add a Placeholder in a React CKEDITOR
- compare 2 objects and adjust the second one based on first in a smarter way
- How to simplify a javascript function into clean readable code?
- after entering the value in the textbox if I hit enter, should see a new chip with the entered value in it
- Why does the newer 'setState' method not recognize my event.target?
- React Error - Cannot read property 'state' of undefined
- How can I store my JWT Token in localstorage?
- Netlify throwing errors on my Gatsby JS about jQuery
- How to rewrite redundant method declaration and create a shorter one?
- how to get current route in react-router-dom v4.2.2
- How to change React parent component size based on child component size without rendering child component?
- How to map and filter JSON with Javascript
- Dynamic response from GraphQL mutation
- Adding scroll to top button is not working with react?
- Understanding async React rendering
- How to add multiple icon to the options in react-select?
- ReactJS - Error: Objects are not valid as a React child
- Axios sends a post to the duplicate url
- React - Dynamically Render Select Options
- Extend Enzyme js