How to use useState and useEffect in functional components.

Photo by Camille Orgel on Unsplash

What are hooks?

  • Hooks cannot be used inside a condition, loop or nested function.
  • Hooks cannot be called from a class component or regular java script functions.

You can find out about class component life cycle methods from following.

useState hook

  • A value to access.
  • A function to change the value.
const [name, setName] = useState("Yashod");

Following is a basic demo of useState hook.

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;

But there is a safe way of update the state which is using the previous state as in the class component as follows.

setCount(prevCount => prevCount - 1);

Important — If you need to initialise a value from a complex function then there is a special way of use useState or else it will execute in every update which will decrease the performance.

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;

There is an other variation of useState using previous value as follows.

const increment = () => {
setObj(prevObj => {
return { ...prevObj, count: prevObj.count + 1 }
});
};

useEffect hook

useEffect({
// code
}, []);

The array at the latter part will contain the states and useEffect is triggered only if those states are changed.

There are several cases that you need to know regarding the useEffect.

  • Trigger in every update.
useEffect({
// code
});
  • Only when component is mounted.
useEffect({
// code
}, []);
  • Only when component is unmounted.
useEffect({  return = () => {
// code
};
}, []);
  • Only count is changed.
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

Hopefully this is helpful.

If you have found this helpful please hit that 👏 and share it on social media :).

Technical Writer | Tech Enthusiast | Open source contributor