State And Lifecycle Management with React UseState and UseEffect Hooks.
Hooks, the spice of Functional React introduced in React 16.8.
Table of contents
React Hooks are functions that allow you to use state and other React features in functional components, rather than having to use class components. Hooks allow a more flexible and modular way to write React components, by breaking down component logic into smaller, reusable pieces. They were introduced in React 16.8 as a way to make it easier to write and understand React code and they are undeniably essential to modern react.
useState Hook
The useState
hook is a built-in React hook that allows us to add state to functional components. To use the useState
hook, you have to import it like in the code below, it returns an array containing the current state value and a function to update it.
import React, { useState } from "react";
const [state, setState] = useState(initialState);
setState(newState);
During the initial render, the returned state (state
) is the same as the value passed as the first argument (initialState
). We can then use the setState
function to update the state to newState
.
Note: The function's name doesn't need to have the
set
prefix likesetState
orsetCost
orsetCountry
, but that is just the convention.
Take the example below, here we have an age
state with an initial value of 10
, then using a button's onClick event, we call the setAge
function to increase the value of age
by 1
.
import React, { useState } from "react";
function App() {
const [age, setAge] = useState(10);//so initially, age is set to 10
return (
<>
<!--the button below increases age by 1-->
<button onClick={() => setAge(age + 1)}>INCREASE AGE</button>
<h3>I am {age} years old!</h3>
</>
);
}
export default App;
If we update a state's value to the same value as the current state, React will ignore and won't re-render because React uses the Object.is
comparison algorithm to compare the previous and current values. However, when the useState's function is called and a state's value is changed, it triggers a re-render, keep this in mind, you'll need to remember it when dealing with the useEffect
hook.
useEffect Hook
The useEffect
hook is a built-in React hook that allows us to add lifecycle methods and side effects to functional components. It accepts a function (also called an effect) that will run by default after the component has been rendered. This function can be used to perform tasks such as fetching data, setting up event listeners, or updating the DOM.
Here's an example of the useEffect
in-action, here, we use the useeffect
to add a side effect (a change in the body's background color) to occur whenever the component has been re-rendered. Once the button is clicked, the setValue function will update the state value and trigger a re-render, which will then trigger the side effect in the useEffect
.
import { useState, useEffect } from 'react';
export default function App() {
const [value, setValue] = useState(0);
useEffect(() => {
if (value < 10) {
document.body.style.backgroundColor = `#aa34${value}${value}`;
}
});
return (
<>
<h2>{value}</h2>
<button className="btn" onClick={() => setValue(value + 1)}>
Increase
</button>
</>
);
}
UseEffect
also lets us conditionally perform effects with a dependencies array. This dependencies array
is the second argument passed to useEffect
. In this example, the effect will only run when value
changes.
useEffect(() => {
if (value >= 1) {
document.title = `${value} New Messages`;
}
}, [value]);
Once any one of the values in the array changes, the effect function runs again, however, if the dependencies array is empty, like below
useEffect(() => {
if (value >= 1) {
document.title = `${value} New Messages`;
}
}, []);
useEffect
will only run on the first render.
Often, when a useEffect
runs, it leaves resources that need to be removed before the next instance of useEffect
is run. To do this, we can add a function to the useeffect hook which will be used to clean up left-over resources.
useEffect(() => {
if (value >= 1) {
document.title = `${value} New Messages`;
}
return () => {
document.title = 'My React Site';
};
});
This function is called the clean-up function. Therefore, if a component is re-rendered repeatedly, a clean-up function will clean up the previous effect before the next effect is run, it is a good way to avoid memory leaks.
Conclusion
The UseState and UseEffect hooks are essential tools for building robust and efficient React applications. By understanding how to use these hooks effectively, we can build complex applications with ease and enhance the user experience. Overall, the UseState and UseEffect hooks are powerful tools that can help us build better React applications.
Thank you for reading! I hope this article was helpful. Kindly like and share it with your friends and colleagues if it was. I would love to connect with you on Twitter and Github.