Response 19: From server functions to optimistic updates

0
14
Response 19: From server functions to optimistic updates


According to a bad saying, some JavaScript frameworks have a shelf life shorter than a liter of fresh milk. This does not apply to React for several reasons. On the one hand, the library celebrated its tenth birthday last year, making it one of the “oldest pieces” in the web world. React is also exercising restraint when it comes to release frequency: the last major release appeared in June 2022. Only a few bug fixes have been released since then.

Advertisement


After a Release Candidate phase that lasted several months, this was only changed on December 5, 2024 Final version of React 19 Was published. It includes not only new functions and hooks, but also entirely new concepts that aim to pave the way for full stack development in React.




Nils Hartmann is a freelance software developer and coach, focusing on Java in the backend and React in the frontend, for which he also gives workshops and training.

New functions for working with a website’s metadata fall into the category of small but useful innovations in React 19. Metadata is like DOM elements title, meta Or link In head-Area of ​​the Dome. Therefore, they are usually not part of the React component hierarchy and cannot be easily used with React on-board tools. Instead, libraries are used in many projects.

With React 19, these elements are now also available in JSX and can therefore be used in every component. React makes sure elements are placed in the right place at runtime head-Element wandering. If there are multiple such elements in a component hierarchy, the element that is lowest in the component hierarchy “wins”.

The following list demonstrates this behavior using title-Element. The App component sets the title of the browser window to “Blog Application”. if subcomponent BlogPost Also rendered, the subcomponent overwrites the title so that it now matches the title of the displayed blog post.

function App({postId}) {
  return 
Blog Application {!!postId && }
} function BlogPost({postId}) { const post = useBlogQuery(postId); return
{post.title} {/* ... */}
}

In addition to titles and other metadata, you can now also script-Render elements and external stylesheet files directly in a component. Here too, React ensures that the appropriate script– respectively linkElements are placed at the beginning of the DOM and ensure that a component is only rendered when the browser loads the appropriate resources. This makes it much easier to work with dynamically added scripts (for example from external providers like the Google Maps API) or style sheets. Metadata features are completed by the ability to preload resources. developers can do this head-DOM elements specify resources such as style sheets or fonts that the browser pre-downloads in the background so that it is available locally when needed. With React 19 it is possible to specify such resources in code. React then takes care of creating the corresponding DOM elements.

A particular challenge in React applications is optimizing or saving rendering cycles. React basically re-renders a component as soon as its state changes, including its subcomponents. There isn’t as much granular tracking of changes in React as there is with Signals in Angular. This is not necessarily a problem as rendering is usually very fast, as changes only occur to the virtual DOM and React reduces potentially expensive changes to the DOM to an absolute minimum. But with deep component hierarchies or complex components, this can cause performance issues. that’s why it exists memo-Function that can cache a prepared component, as well as hooks useMemo And useCallbackTo cache data or functions within a component.

However, using these three functions is error-prone because the mechanism React uses to check whether cached objects are still valid or need to be recreated uses reference comparison. As soon as a reference is (accidentally) created repeatedly, the cache is actually clogged. Other than that, just worry useMemo– And useCallback– Quickly calls component functions for confusing code.

The new React compiler aims to mitigate these problems. Through this, React developers should be exposed in many places. memo, useMemo And useCallback Can do without. The compiler analyzes the written code and then produces optimized code as output that behaves similar to today’s handwritten code. memo, useMemo– And useCallback-The call works and thus ensures great updates.

react compiler is an independent project And will appear independently of the React 19 release.

Teams already has a date for the arrival of real-time translation in video callsTeams already has a date for the arrival of real-time translation in video calls

Minor simplifications have also been made to the existing API. that’s how it is refThe attribute has become a generic property that – like all other properties – can be declared and used in a component’s properties. somewhat complicated forwardRef-The function becomes redundant and is marked as deprecated by the React team. Creating and presenting context has also become easier to some extent. createContextThe function returns the provider component directly in the future. The division into consumer and provider components is no longer necessary as the consumer component has been replaced by the introduction of hooks. useContext It has not been needed for a long time.

Regardless of how the reference is made, it is accompanied by use-Create a new way to access it – or a promise – within a component. Against of useContext Is use-The function is not a hook (so it is described under API and not under hooks in the documentation) and therefore it is not subject to the “rules of hooks”. Accordingly, a hook function, for example, cannot be used ifAre called statements. useThe -function can be used like any other normal function.

The next listing reflects this behavior. CounterContext Required in the component only when the checkbox is clicked, otherwise the component will not use its data. with useContext However, the context will always have to be queried, regardless of the state of the checkbox. with use The component queries the context only if the checkbox is clicked accordingly. This has an impact not only on the code, but also on the runtime: until the checkbox is clicked and hence the context is not included use Questioned, React also doesn’t re-render the component when the value of the context changes. When using with useContext The component is re-rendered even if the value of the context is not actually required (the checkbox is not clicked).

export const CounterContext = createContext(null);

function CounterContextProvider{children}) {
  const value = { /* ... */ }

  // bisher:
  return {children}

  // React 19:
  return {children}
}

function CounterDisplay() {
  const (selected, setSelected) = useState(false);

  const counter = selected ? use(CounterContext) : null;

  return (
    
{counter &&

Aktueller Wert: {counter.value}

}
); }

Many new possibilities exist when working with asynchronous actions, such as reading and writing server-side data. React 18 has already introduced the change. This allows interface updates to be prioritized. Typically, changing a state causes React to immediately re-render the component and the updated user interface (UI) is immediately visible in the browser.

Developers can use transitions to specify callback functions. There the position of the component can be changed. However, the component is now rendered in the background. The existing UI does not change initially. The UI updates only after background rendering is completed.

This behavior is especially useful for updates that take a very long time and would otherwise block the UI. With a transition, recalculation occurs in the background and the “old” UI remains in place until background rendering is successful. For example, so that a component can display an indication of a current update, a transition provides information about whether it is currently running or not.

The listing shows this behavior in the React 18 version using a very simple example:

function Counter() {
  const (count, setCount) = useState(0);
  const (isPending, startTransition) = useTransition();

  const handleClick = () => {
    startTransition(() => {
      setCount(c => c + 1);
    });
  };
  
  return 
{isPending &&

Darstellung wird aktualisiert.

}
}

want here CounterView be a complex subcomponent and after changing count-It takes some time to render the state. Due to transitions in which the state changes, rendering occurs in the background. Feedback now renders immediately Counter-Component is new, but quits count-Initially tell its current value. However, it delivers useTransition-call now true For isPending Back. So the component can immediately display the “Display is being updated” information. The component is now re-rendered in the background. there is count set to new value and isPending Is falseTherefore the component can represent a representation of the future. Once rendering is complete, React replaces the old rendering with the new one. If an error occurs while rendering in the background, React removes the new rendering without replacement.

What’s new in React 19 is that the function used as a transition callback can be asynchronous. Such actions are called actions. This can be used, for example, to move a server call into a transition. The previous representation is then retained until the asynchronous server call completes. Like the previous example, React provides information about whether a transition is in progress, so a wait message may appear.

The list shows a transition with an asynchronous action using a component that represents a button with a similar counter:

async function registerLikeOnServer() {
  // Server-Call z. B. mit fetch ausführen
  // neue Likes vom Server zurückliefern...
}

function LikeButton({initialLikes}) {
  const (likes, setLikes) = useState(initialLikes);
  const (isPending, startTransition) = useTransition();

  const handleClick = () => {
    startTransition(async () => {
      const newLikes = await registerLikeOnServer();
      setLikes(newLikes);
    });
  };

  return 
}

Clicking the button executes a server call, which increments the number of likes on the server and returns the new number (the code for this is React-independent and has been removed from the listing for simplicity). After clicking the button, React immediately re-renders the component with the old state, supplying isPending But true Back. This means that the button can be used when saving disabled-View status. The server call is already running in the background. Once this is complete, the state is reset and the component is rendered and displayed in the new position.




(Image: WD Ashari/Shutterstock.com)

enterjs 2025 Will take place in Mannheim on 7 and 8 May. This conference offers a comprehensive look at the JavaScript-powered enterprise world. The focus is not only on the programming languages ​​JavaScript and TypeScript, but also on frameworks and tools, accessibility, practical reports, UI/UX, and security.

The program is expected to go live in mid-January. till then you can get discount Blind Bird Tickets in Online Shop To acquire.

Cloudland 2025: New location and new ideas for cloud native festivalCloudland 2025: New location and new ideas for cloud native festival

LEAVE A REPLY

Please enter your comment!
Please enter your name here