React Hooks | New Hooks introduced in react 19.

Basic Hooks(v.16.8.0) and new hooks introduced in react v.19.

Ashwini Pachare
4 min readApr 7, 2024

INTRODUCTION

Hooks provide a more direct API to the React concepts like props, state, context, refs, and lifecycle. With Hooks, you can extract stateful logic from a component so it can be tested independently and reused.

Hooks allow you to reuse stateful logic without changing your component hierarchy.

Motivation Behind Introduction of Hooks

React often had to maintain components that started out simple but grew into an unmanageable mess of stateful logic and side effects. Each lifecycle method often contains a mix of unrelated logic.

For example, components might perform some data fetching in componentDidMount and componentDidUpdate. However, the same componentDidMount method might also contain some unrelated logic that sets up event listeners, with cleanup performed in componentWillUnmount. Mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method. This makes it too easy to introduce bugs and inconsistencies.

To solve this, Hooks let you split one component into smaller functions based on what pieces are related rather than forcing a split based on lifecycle methods. You may also opt into managing the component’s local state with a reducer to make it more predictable.

STATE HOOK (useState)

We call useState inside a function component to add some local state to it. React will preserve this state between re-renders. useState returns a pair: the current state value and a function that lets you update it. You can call this function from an event handler or somewhere else. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together.

import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
// Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Update Count
</button>
</div>
);
}


//You can use the State Hook more than once in a single component:

function ExampleWithAdditionalStates() {
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
}

EFFECT HOOK (useEffect)

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API

import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});

return (
<div>
<p>You clicked { count } times < /p>
<button onClick = {() => setCount(count + 1)}>
Update Count
</button>
</div>
);
}

New Hooks introduced in react 19.

USE HOOK (use())

This hook will simplify how we use promises, async code, and context.

import { use } from "react";

const fetchUsers = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
return res.json();
};

const UsersItems = () => {
const users = use(fetchUsers());

return (
<ul>
{users.map((user) => (
const {id = "",name = "",email = ""} = user || {};
<div key={id}>
<h2 className='fw-600'>{name}</h2>
<p>{email}</p>
</div>
))}
</ul>
);
};
export default UsersItems;

USE_FORM_STATUS HOOK (useFormStatus())

This new hook will help you have more control over the forms you create. It will give you status information about the last form submission.

import { useFormStatus } from "react-dom";

function Submit() {
const status = useFormStatus();
return <button disabled={status.pending}>{status.pending ? 'Submitting...' : 'Submit'}</button>;
}

const FormStatus = () => {
return (
<form>
<Submit />
</form>
);
};

export default FormStatus;

USE_FORM_STATE HOOK (useFormState())

This new hook is useFormState. It allows you to update state based on the result of a form submission.

const [state, formAction] = useFormState(fn, initialState, permalink?);//syntax
  1. fn: the function to be called when the form is submitted or button is pressed.
  2. initialState: the value you want the state to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.
  3. permalink: this is optional. A URL or page link, if fn is going to be run on server then the page will redirect to permalink.
import { useFormState} from 'react-dom';

const [ message, formAction ] = useFormState(submitForm, null)

const FormState = () => {
const submitForm = (prevState, queryData) => {
const name = queryData.get("username");
if(name === 'john'){
return {
success: true,
text: "Welcome"
}
}
}

return <form action={formAction}>
<label>Name</label>
<input type="text" name="username" />
<button>Submit</button>
{message && <h1>{message.text}</h1>}
</form>
}

export default FormState;

RULES OF HOOKS

Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.

Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions.

As of now, all the hooks mentioned above (React 19) are available in the canary release. As suggested by the React team, do not use these for customer/user facing apps at the moment.

Happy Coding 👩‍💻🧑‍💻

--

--