"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > React The new updates

React The new updates

Published on 2024-07-31
Browse:546

React  The new updates

This week, we will be talking about the new React 19 updates and hooks. Having gone through and using some of these new updates, I can only agree that it has simplified some of the rigorous activities developers go through when building apps, especially interactive form-related applications.

Join me and let us explore some of these new updates.

React Compiler: The React compiler picks your React code, translates it into a JavaScript code for the browser, and manages the state of your component or User Interface. This singular action helps to optimize the performance of your application.

If you are familiar with the useMemo hook, useCallback hook, and the React.Memo, you will understand that they help memoize (storing of values or functions for future uses) your components, so they don't have to re-render when there are no state changes. When there are changes in state, React re-renders the component in question, and its children, and when there are no changes in your code, the component stays as is keeping the previous memory, value and state in the component or hook for future uses; thereby optimizing the performance of your components. This is exactly what the React Compiler does automatically, without having to call any of the aforementioned hooks manually.

Form Actions: One of the biggest advantages of using React is the management and mutation of state, and this mostly happens when we use elements. Forms help us create and handle user interactivity more effectively.

With form actions, you don't need event handlers like onSubmit and onChange to effect live mutation of data, instead we can pass an action prop to the

element which receives a function that triggers the event.
const myFunction = async (formData) => {
  const [name, setName] = useState("")

  const updatedName = await nameChange(formData.get("name"))
     setName(updatedName)
}

With this approach, we don't need the application of useState to mutate data through event.target.value, Instead, in myFunction we can get the mutated data through an argument.

It means from the element in our form, we have to set a name attribute. Using this method means we allow React handle the form itself through the Native React form Object instead of manually changing state through event handlers.

Server Components: React 19 allows for components to be rendered on a server before bundling, in a separate environment from the client application or SSR server setup. The Server components are not the same as SSR (server side rendering), but a separate server environment in React Server Components.
This feature allows for components to pre-render before time, thereby resulting in fast content displays and improved load time.

Metadata: React 19 allows for a flexible metadata. Developers can manage the title, description and other meta tags of individual components through the DocumentHead component. This will help to improve SEO (Search Engine Optimization).

Const AboutUs = () => {
 return (
    
      Learn more about our company
      
      // content
    >
  );
}

React 19 has a series of new hooks, some, new, others an improvement to existing hooks. Let's discuss about them below.

The use() hook: The use hook is an experimental API that can directly be used to read the value of a Promise or context within a component or hook (which is its only known limitation for now).
The use hook is very versatile and can also be used in place of useEffect, as It can be used for asynchronous data fetching. This helps to
achieve a neater and concise code block.

Caveat: It is not a replacement for useEffect because it still has its own limitations that _useEffect _will execute without limits.

import {use} from "react"
const fetchData = async () => {
    const response = await fetch("https://........");
    return response.json()
}

const userData = () => {
    const user = use(fetchData());

        return (
    
{user.name}
); }

useActionState(): This is a new hook that helps to manage state changes. It helps to manage pending state, error handling, and final
state updates. The useActionState _works like the _useReduce _in that it receives two(2) parameters: the function to be called when the form is submitted, and an _initialState, and it returns an array containing three(3)values: the state, which is now the current state if there is a mutation of state, a new action(formAction) that can be passed as a prop in our form component to call the server action, and _isPending _that returns a _boolean _value if or not the form is submitted.

import { useActionState } from "react";

async function incrementFunction(initialState, formData) {
  return initialState   1;
}

function StatefulForm({}) {
  const [state, formAction, isPending] = useActionState(incrementFunction, 0);

  console.log(state);

  return (
    
) }

From this example, the incrementFunction adds 1 to the state every time the button is clicked. The initialState being 0, and then increases to 1 at the first click of the button, thereby changing the state to 1, and for every other click on the button adds 1 to the last state of the component.

useOptimistic() hook:

This is a new hook that allows users to see the outcome of their action even before the pages load completely. The pages are optimistically rendered to the user even when the server is still in its data fetching mode.

With the hope that data fetching will be successful, React displays the intended result to the client, and when data fetching fails, React reverts to the value of the previous state in order not to display incorrect data. This singular action helps in a seamless and fast display of data thereby improving user experience.

useFormStatus():

As the name implies, useFormStatus gives us the status of our form or form fields. This hook does not take in any parameter, but it sure returns 4 objects:

pending: This returns a boolean value: true or false. It returns true when the form is submitting, and false when the form is submitted.

data: When the form is successfully submitted, we can get the information of the user or object from the form field like this:

(formData.get("name"))
(formData.get("address"))

method: The default method of a form is GET, unless stated otherwise. We can get the method of our form with .method. When we are submitting a form, a string method property should be specified as a POST.

action: This is a reference to the function that will be passed to the action prop in our element.

The useFormStatus must always be called from a element or a component that is rendered inside a .

There's quite a few more updates that I can't really write about, so you don't get bored having to read so much. You can click on the React Docs Website to check out some of the other updates.

I hope you had a great time learning with me.

Do well to follow me if you enjoyed my articles.

Thanks, and have a great week ahead my friends.

Release Statement This article is reproduced at: https://dev.to/oluwatrillions/react-19-the-new-updates-2k68?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3