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.
**
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:
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!