setState()
enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state.
setState method is asynchronous, and as a matter of fact, it does not return a promise. So In cases where we want to update or call a function, the function can be called callback in setState function as the second argument.
For example, in your case above, you have called a function as a setState callback.
setState(
{ name: "Michael" },
() => console.log(this.state)
);
The above code works fine for class component, but in the case of functional component, we cannot use the setState method, and this we can utilize the use effect hook to achieve the same result.
The obvious method, that comes into mind is that ypu can use with useEffect is as below:
const [state, setState] = useState({ name: "Michael" })
useEffect(() => {
console.log(state) // do something after state has updated
}, [state])
But this would fire on the first render as well, so we can change the code as follows where we can check the first render event and avoid the state render. Therefore the implementation can be done in the following way:
We can use the user hook here to identify the first render.
The useRef Hook allows us to create mutable variables in functional components. It’s useful for accessing DOM nodes/React elements and to store mutable variables without triggering a re-render.
const [state, setState] = useState({ name: "Michael" });
const firstTimeRender = useRef(true);
useEffect(() => {
if (!firstTimeRender.current) {
console.log(state);
}
}, [state])
useEffect(() => {
firstTimeRender.current = false
}, [])