React hooks are functions you can use inside functional components.
useState allows you to manage states inside your components.
useEffect adds side effects to your components.
Side Effects as in:
With this hook, you can run side effects after the rendering of the component, or after the unmounting of the component.
Unmount means, deleting/removing a component from the DOM.
When you return a function inside useEffect, the function will run when the component unmounts, or when the side effect re-runs.
This returned function is called "Clean-up function".
useEffect(() => {
return () => {
console.log('cleanup');
}
});
import { useState, useEffect } from "react";
const Hoge = () => {
const [count, setCount] = useState(0);
const countUp = () => {
setCount(count => count + 1);
}
useEffect(() => {
console.log("component did mount");
}, []);
useEffect(() => {
console.log("component did update");
console.log(`current count is ${count}`);
}, [count])
useEffect(() => {
return () => {
console.log("component will unmount");
};
}, [])
return (
<>
Current count:{count}
<button onClick={countUp}>
count up!
</button>
</>
);
}Returns state and dispatch function (a function to send actions).
By using this hook, you can do state management in a component. So it has similar usage with useState.
{const [state, dispatch] = useReducer(reducer, initial state)}