joe, (edited )

Earlier this week, we started looking at React and I figured that for today’s post, we should take a look at the https://react.dev/reference/react/useEffect and https://react.dev/reference/react/useMemo React Hooks. Hooks are functions that let you “hook into” React state and lifecycle features from function components. In yesterday’s post, we used https://codepen.io/steinbring/pen/GRLoGob/959ce699f499a7756cf6528eb3923f75. That is another React Hook. The useState Hook allows us to track state in a function component (not unlike how we used Pinia or Vuex with Vue.js).

The useEffect React hook lets you perform side effects in functional components, such as fetching data, subscribing to a service, or manually changing the DOM. It can be configured to run after every render or only when certain values change, by specifying dependencies in its second argument array. The useMemo React hook memoizes expensive calculations in your component, preventing them from being recomputed on every render unless specified dependencies change. This optimization technique can significantly improve performance in resource-intensive applications by caching computed values.

Let’s take a look at a quick useEffect, first. For the first demo, we will use useEffect and useState to tell the user what the current time is.

See the Pen by Joe Steinbring (@steinbring)
on CodePen.

Let’s walk through what we have going on here. The App() function is returning JSX containing <p>The current time is {currentTime}</p> and currentTime is defined by setCurrentTime. The code block useEffect(() => {}); executes whenever the state changes and can be used to do something like fetching data or talking to an authentication service. It also fires when the page first renders. So, what does that empty dependency array (,[]) do in useEffect(() => {},[]);? It makes sure that useEffect only runs one time instead of running whenever the state changes.

We can get a little crazier from here by incorporating the setInterval() method.

See the Pen by Joe Steinbring (@steinbring)
on CodePen.

In this example, it still runs useEffect(() => {},[]); only once (instead of whenever the state changes) but it uses setInterval() inside of useEffect to refresh the state once every 1000 milliseconds.

Let’s take a look at another example.

See the Pen by Joe Steinbring (@steinbring)
on CodePen.

In this one, we have three form elements: a number picker for “digits of pi”, a color picker for changing the background, and a read-only textarea field that shows the value of π to the precision specified in the “digits of pi” input. With no dependency array on useEffect(() => {});, whenever either “Digits of Pi” or the color picker change, useEffect is triggered. If you open the console and make a change, you can see how it is triggered once when you change the background color and twice when you change the digits of pi. Why? It does that because when you change the number of digits, it also changes the value of pi and you get one execution per state change.

So, how can we cut down on the number of executions? That is where useMemo() comes in. Let’s take a look at how it works.

See the Pen by Joe Steinbring (@steinbring)
on CodePen.

In this revision, instead of piValue having a state, it is “memoized” and the value of the variable only changes if the value of digits changes. In this version, we are also adding a dependency array to useEffect() so that it only executes if the value of color changes. Alternatively, you could also just have two . Let’s take a look at that.

See the Pen by Joe Steinbring (@steinbring)
on CodePen.

If you throw open your console and change the two input values, you will see that it is no longer triggering useEffect() twice when changing the number of digits.

Have any questions, comments, etc? Feel free to drop a comment, below.

https://jws.news/2024/exploring-useeffect-and-usememo-in-react/

#JavaScript #JSX #React #ReactHooks #VueJs

  • all
  • All
  • Subscribed
  • Moderated
  • Favorites
  • javascript
  • ethstaker
  • DreamBathrooms
  • Durango
  • magazineikmin
  • everett
  • cubers
  • Youngstown
  • khanakhh
  • slotface
  • rosin
  • vwfavf
  • mdbf
  • kavyap
  • ngwrru68w68
  • megavids
  • InstantRegret
  • GTA5RPClips
  • cisconetworking
  • Leos
  • thenastyranch
  • osvaldo12
  • modclub
  • tacticalgear
  • tester
  • anitta
  • normalnudes
  • provamag3
  • JUstTest
  • All magazines