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 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.
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.
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.
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.
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.
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 …
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.
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.
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...
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.
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 <Foo /> component? What selector should I use for that style? I have no idea what <Foo /> 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 <Header /> a header CSS selector is probably right. But what if <Header /> 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.
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?
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?