https://octospacc.altervista.org/wp-content/uploads/2024/03/image-6-960x960.pngI side #projects non finiscono mai: ogni volta vengono quelle #idee che devono per forza essere stuzzicate… e puntualmente ciò che doveva essere un progettino di 1 giorno o 2 si protrae sempre più a lungo (e se non è tecnicamente già successo, sta nell’aria), e da #progetto collaterale diventa un nuovo progetto principale. E i #progetti precedenti? Beh… diventano a loro volta secondari! 😬️Praticamente, qualche settimana fa pensavo che avere una roba simile alla #fotocamera DSi (si, ormai quello è un chiodo fisso nel mio cervello, anche se mezzo arrugginito, e l’articolo non è ancora finito) ma open-source e per dispositivi #mobile moderni sarebbe figo, si può sviluppare qualcosa di versatile e potente… però non avevo personalmente iniziato nulla. Da però qualche giorno ho pensato di voler creare una piccola #webapp semplificata per fare questi memini con le scritte, e magari pure varie decorazioni (per il momento sto usando GIMP, che è molto tedioso). Stamattina ho pensato… “Perché non unire tutte e due le cose? Una versione molto basica riesco a farla in qualche giornata scarsa…”… si si 🤣️
Beh, non iniziamo al meglio, perché la prima metà giornata l’ho spesa a pensare “hm ok voglio qualcosa di multipiattaforma”, ma “il mio amore #web vanilla non va bene perché su telefoni più scrausi con camere marce non girerebbe bene, e quindi “vabbé quasi quasi provo #React Native”, solo che “ah mi sa che per avere un canvas di disegno su tutti i target di build devo usare questa libreria particolare”, peccato che “aiuto è un casino tra documentazione e dipendenze dell’ambiente non so cosa è più mentale”, e quindi “aspetta ma se usassi Godot?”, per poi scoprire che “mannaggia solo la versione iOS di Godot supporta le fotocamere (non ci godo[t])”, e allora “vabbé, Unity funzionerá”, e quindi via con la pazienza di installare un SDK LTS vecchio che supporta ancora Android KitKat (è stato lentissimo sulla mia VM cloud), peccato che poi “aiutoooo Unity è complicatissimo è impossibile fare qualsiasi cosa senza soffrire”, e anche se “magari ci sono altri engine #multipiattaforma che fanno al caso mio?”, purtroppo “no, non esiste un bel niente”. 😶🌫️️
E comunque alla fine mi sono convinta che in qualche modo questa cosa l’avrei fatta funzionare per forza su #ReactNative, che di tutte le probabili #soluzioni mi sembra ancora quella meno malata; per fortuna, #giochicchiando fino all’ora precedente (con non poca confusione), ho tirato su una base che mi dimostra all’atto pratico che ciò che mi serve è facilmente implementabile. Quindi, essendo la domanda del perché sempre esaurita da un “perché no?”, e risolto il dubbio del come, ora l’unica cosa che mi chiedo è il quanto… quanto #tempo e sudore prima di pubblicare la prima grezza build online? 💀️ (Ammesso che vada tutto liscio, perché sulla carta ora dovrebbe, ma nella pratica non ho ancora testato il funzionamento su Android, solo quello via browser…)
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.
I don't particularly like #React, up until a few weeks ago I hadn't touched it in years, but even with that I have to toot my own horn and say I'm writing some very performant and bug free apps with it (at least in my own code).
It sucks when you're forced to use someone else's design system that only supports React, but at least I've resigned myself to not fight it anymore.
So I am slowly digesting the official tutorial for remix.js & I am finding it a pleasant experience.
They have tried to clean up the React meta framework experience.
I have used Next.js & vanilla react.js in the past, but I can see myself using Remix.js, especially now that Shopify have adopted it as well.
I am curious why are react people not interested in Remix.js?
This is a logical question I am not trying to attack someone's personal preference.
Having some fun time playing with react-reconciler. Not sure if this idea will come to fruition, but I'm hoping to at least get it into a demo-able shape.
I don't know if I have energy or desire to finish it given the limitations (I realized really late that you can't marshal ReactSyntheticEvent), but it was super fun!
The demo looks a bit plain, but all the fun stuff happens under the hood. The UI is translated to real DOM nodes in the renderer (UI process of Electron), but the state (callbacks, count) is actually managed by the main process (aka backend of Electron).
My extended goal with this exercise was to do something like Server-Side Rendering between Electron's Main and Renderer processes. For that to be complete I would need to introduce some sort of boundary class that would let me wrap the components on the server-side (main process), and let client-side (renderer process) actually hydrate them.
I might give it a go a bit later, but I'm quite satisfied with what I got so far!
Aha! It was actually easier than I thought and I managed to do a simplified version that doesn't yet support syntactic sugar of 'use client’. Check this demo out!
The red area is pre-rendered in the main process (server), and the green one is a client component that lives in the renderer process (client). The most important bit is that the main process state (useState and such) is preserved on the refresh, while the renderer process starts afresh!
Here is the component's source. As advertised the boundary between client/server components is a bit raw, but that can be polished away given further interest!
Ready to take your Drupal decoupling game to the next level?
Join us for a deep dive into leveraging Handlebars, a lightweight JavaScript templating tool, to create decoupled menus easily in decoupled, headless, or progressive decupled applications with Marcelo Vani.
In this session, we'll walk you through a live demonstration of implementing a decoupled Admin toolbar using Handlebars in three simple steps. Say goodbye to complex package management and compilation headaches – Handlebars streamline the process, making it accessible to developers of all skill levels.
Following this, we will have a project showcase and a story from a group of Suffolk local residents with various skills and enthusiasm. They have completed three innovative local history projects using Drupal with plenty of public involvement and praise from respected local historians and local history groups: StreetStroll, Our Fallen and SkyLine. Hear more from Joe Thompson about the importance of the projects and how Drupal has helped with these exciting and impactful projects.
Reserve your spot today and participate in this exciting event at The Children's Society in London on the 26th (Tuesday) for an engaging session packed with practical insights and an informative and actionable Drupal Meetup this March 2024!