...

/

Test Driving the useEffect Hook

Test Driving the useEffect Hook

Learn about creating practical applications in React with useEffect hook, addressing common challenges and best practices for effective usage.

Delving into the useEffect hook

The effect callback is defined in the useEffect hook's first input argument:

function Title() {
useEffect(() => {
window.title = ""; // Setting the window title to an empty string
});
}
React component effect to set the window title to an empty string

JavaScript ES6 syntax and closures in useEffect hook

The most common way of using the createThe create function represents the side effect that the useEffect hook is designed to execute. It is a callback function containing the logic or actions to be performed when the effect is triggered. function can be defined by using the JavaScript ES6 syntax with an inline function, () => {}. One of the interesting facts about this effect function is that, thanks to JavaScript closuresClosures are powerful and commonly used in JavaScript for various purposes, such as creating private variables, implementing data encapsulation, and facilitating the creation of functions with persistent state., it can access all of the variables defined in the functional component:

function Title({ text }) {
const a = 2;
useEffect(() => {
console.log(a); // Logging the value of 'a'
console.log(text); // Logging the value of the 'text' prop
});
}
Logging constant, a, and text prop to the console

The create callback function in the preceding code references both the a variable and textWithout the JavaScript closure, both variables would have to be passed into the inline function explicitly through the input arguments.

Managing state changes with useEffect hook

Another interesting fact about the useEffect hook is that the effect is a callback where it's quite common to see an effect involving a state changed inside. Let's take a look at one example:

Press + to interact
A button with clickable text
A button with clickable text

Let's say we have a Title component that gets a text prop. Inside, it has a button. When this ...