Home > Web Front-end > JS Tutorial > body text

Top eact Hooks

Susan Sarandon
Release: 2024-09-26 07:31:42
Original
546 people have browsed it

Top eact Hooks

What are React hooks?
Hooks provide functional components the ability to manage state & side-effects. They were first introduced in React v16.8 and different hooks have been added since then. Today we will be talking about MY top 3 hooks which i use the most.

**

  1. The useState hook ** It let's you add a state variable inside a component.

const [age, setAge] = useState(18)

The above is a simple example to how this hook is defined.
The useState hooks takes a paramter (18) as an initial state for the defined variable (age) and provides us with an array of two values:

  1. (age) which returns the current state
  2. (setAge) which is a setter function that lets you update the state.

Here is how a setter function works:

function incrementAge(){
setAge(a => a + 1)
}

Each time this function is called, the setter function will update the state based on the last state.

2. The useEffect hook
It lets you synchronize your component with an external system like the DOM, networks... .

useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);

The useEffect hook takes 2 parameters, a function and a dependency array. The function will only execute when the variables in the dependency array, which comes after the function, change it's value or state. If the dependency array is empty, the function will run each time the component gets rendered.

These are just two of many other hooks in React, they are the most common and the most useful in different situations.

The above is the detailed content of Top eact Hooks. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template