Simulating componentDidMount() & componentDidUpdate()

Updating a state automatically re-renders the component and then fires the callback in useEffect().
function Example() { const [A, setA] = React.useState(0); const [B, setB] = React.useState(0); React.useEffect(() => { // similar to componentDidMount() & componentDidUpdate() if (A>5) return; setA(A+1); setB(1); }); // no second argument -- default -- firing after every render return (<div>{A} {B}</div>);}ReactDOM.render(<Example/>,document.querySelector("div"));
By default, the callback in useEffect() is fired after every render and any state update. 6 1
If a second argument, [A] or [A,B], is passed as the second argument to useEffect(), the callback is fired as long as any of the props or states in the dependency list (the second argument) has changed since it is last called. 6 1
If an empty array, [], is passed as the second argument to useEffect(), the callback is always only fired once on mount and another time on unmount. 1 1
If the prop(s) or state(s) in the dependencies list (such as [B]) has not changed, the callback won't be fired. 2 1

If you want to fetch data in an AJAX call (5.4), you should use this hook.