joe, (edited ) to javascript

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

joe, (edited ) to javascript

Over the years, we have looked at jQuery, AngularJS, Rivets, and Vue.js. I figured that it was time to add React to the list. Facebook developed React for building user interfaces. The big difference between Vue and React is that React uses one-way binding whereas Vue uses two-way binding. With React, data flows downward from parent components to child components and to communicate data back up to the parent component, you would need to use a state management library like Redux. React is also a library where Vue.js is a framework, so React is closer to Rivets. You can run React with or without JSX and write it with or without a framework like Next.js.

Let’s look at how binding works in React and how it compares to Vue. In Vue, if we wanted to bind a form input to a text value, it would look like this

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

… and to do the same thing in React, it would look like this

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

You will notice that the React version uses the useState React Hook. Where the Vue version uses const inputText = ref('Blah Blah Blah'); for reactive state management, React uses const [inputText, setInputText] = React.useState('Blah Blah Blah'); to manage state. Also, Vue has two-way binding with the v-model directive but with React, the text updates when the state changes, but the state doesn’t automatically update when the input is edited. To deal with this, you manually handle updates to the input’s value via an onChange event. The developer is responsible for triggering state changes using the state updater functions in React. Another big difference is that Vue uses a template syntax that is closer to HTML while with React, JSX is used to define the component’s markup directly within JavaScript.

Let’s take a look at one more example

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

This example is very similar to what we had before but now there are child elements for setInputText(event.target.value)} /> and <TextDisplay text={inputText} />. This approach promotes code reusability. By encapsulating the input field and display logic into separate components, these pieces can easily be reused throughout the application or even in different projects, reducing duplication and fostering consistency. It is kind of the React way. Each component is responsible for its own functionality — InputForm manages the user input while TextDisplay is solely concerned with presenting text. This separation of concerns makes the codebase easier to navigate, understand, and debug as the application grows in complexity.

Have a question, comment, etc? Feel free to drop a comment.

https://jws.news/2024/it-is-time-to-play-with-react/

joe, to random
@joe@toot.works avatar

I’m working on figuring out React as a long-time Vue developer. That #JSX syntax is a bit of a mind f#%k.

pauleveritt, to typescript
@pauleveritt@fosstodon.org avatar

Did some @eleventy stuff with @khalidabuhakmeh on our latest effort to bring #TypeScript #JSX #Vitest tooling into our fave web tool.

And decided -- hell, let's make a video!

https://www.youtube.com/watch?v=SwcJ-JF0cSA

khalidabuhakmeh, to typescript
@khalidabuhakmeh@mastodon.social avatar

So @pauleveritt and I just published the first episode of Strongly Hyped, where we discussed adding , , and to @eleventy.

If you're interested in or , watch it.

Appreciate the likes, shares and subscribes. Cheers!🍻

https://youtu.be/SwcJ-JF0cSA

cmmdmx, to react
@cmmdmx@mastodon.social avatar

Some people may hate it... but I think I'll try to build (yet another) static site generator based on #React / #JSX. It will result in static sites that even work without #JS though 😅 Or at least js is optional, just for explicit features.

I tried different static site #frameworks, but I hated all of them. Building user interfaces with JSX is so superior, live rendering with js/react just isn't. But it's also not needed for static sites, so...

mike, to webdev
@mike@jammer.social avatar

It's a subtle thing that few people will notice, but I've made progress correcting the #Aria structure of #LDJam's generated #HTML (#JSX).

If nothing else, the Aria accessibility guidelines are a fantastic resource for learning how to correctly structure your document, things like what should actually go inside the <body> (i.e. Landmarks), etc.

develwithoutacause, to random
@develwithoutacause@techhub.social avatar

Playing a bit with #Preact / #JSX today and am feeling the pain of not having host elements. I've realized that because a "component" is really just a #VDOM template, there is no implicit contract around what it actually rendered.

As an arbitrary example, what if I want to set a style on a &lt;Foo /&gt; component? What selector should I use for that style? I have no idea what &lt;Foo /&gt; will actually generate, or even how many top-level elements it will output. The Foo component must expose some kind of className or other API to provide this behavior, it's not implicit at all.

Maybe this is good because it provides stronger encapsulation. But it can also lead to bugs. If I render &lt;Header /&gt; a header CSS selector is probably right. But what if &lt;Header /&gt; actually renders:

<div>
<header>...</header>
</div>

Then a header selector isn't actually the top-level element and my style could easily be wrong.

Just some idle thoughts about the lack of host elements.

outofcontrol, (edited ) to webdev
@outofcontrol@phpc.social avatar

Reading ‘Why Tailwind CSS Won’ and was caught off-guard by this comment from Matt Rickard “few developers are writing HTML (instead, they are writing JSX or TSX).” What do you write mostly?

#tailwind #html #jsx #tsx

vanilla, to webdev
@vanilla@social.spicyweb.dev avatar

Chris Coyier @chriscoyier presents some examples of using #JSX without React and talks about other flavors of JSX like @astro and even #Preact SSR:

https://thathtml.blog/2023/08/vanilla-jsx/

#WebDev #HTML

manlycoffee, to CSS
@manlycoffee@techhub.social avatar

Why don't some people like CSS-in-JS?

Is it because code written in CSS-in-JS don't allow you to take advantage of the "cascading" nature of CSS?

Is it because you can't take advantage of selectors?

Is it because there might be some compilation steps required when employing CSS-in-JS? And if compilation isn't used, there might be some render-time slowdown?

?

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