How to use useState and useEffect in functional components.

Photo by Camille Orgel on Unsplash

What are hooks?

useState hook

const [name, setName] = useState("Yashod");
import React, { useState } from "react";const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};

const decrement = () => {
setCount(count - 1);
};

return (
<>
<p>{count}</p>
<button onClick={() => increment()}>Increment</button>
<button onClick={() => decrement()}>Decrement</button>
</>
);
};
export default Counter;
setCount(prevCount => prevCount - 1);
const [count, setCount] = useState(() => {
function()
});

Handle Objects with useState

import React, { useState } from "react";const ObjectState = () => {
const [obj, setObj] = useState({ count: 0, name: "Amal" });
const increment = () => {
setObj({ ...obj, count: obj.count + 1 });
};


return (
<>
<p>{obj.count}</p>
<p>{obj.name}</p>
<button onClick={() => increment()}>Increment</button>
</>
);
};
export default ObjectState;
const increment = () => {
setObj(prevObj => {
return { ...prevObj, count: prevObj.count + 1 }
});
};

useEffect hook

useEffect({
// code
}, []);
useEffect({
// code
});
useEffect({
// code
}, []);
useEffect({  return = () => {
// code
};
}, []);
useEffect({
// code
}, [count]);

Common mistake done in useEffect

const [a, setA] = useState(1);
const [b, setB] = useState(5);
// Do not do - Infinite loop
useEffect({
setA(3);
});
// Do not do - Infinite loop
useEffect({
setA(3);
}, [a]);
// Can do
useEffect({
setA(3);
}, [b]);

References

Technical Writer | Tech Enthusiast | Open source contributor