Introduced in version 16.8, React Hooks are a revolutionary addition to React that allows you to incorporate functionalities from Class-Based components into functional components. This first part of the blog focuses on key features like useEffect and useState.
Why were Hooks developed?
The introduction of Hooks addresses the complexity associated with classes in React. Classes often demand more code and can quickly become unwieldy in large applications. Grasping the 'this' concept, unnecessary binding of event handlers, and scattered logic within lifecycle methods can pose challenges when learning React with classes.
Hooks provide a streamlined approach, enabling the use of state and other React features without the need to write full classes. This enhances code readability and comprehension, particularly in larger projects.
What is a Hook?
A Hook is a special function that grants access to specific React functionalities. By using these functions, we can easily add state to functional components without the need to convert them into class-based components.
useState – Managing State in Functional Components
If you want to use state in functional components, utilize the useState hook. This hook declares a state variable, as demonstrated in the example below where we name it "weather":
import React, { useState } from 'react';
const VoorbeeldComponent = () => {
const [weather, setweather] = useState('Sunny');
}
The useState hook returns two values: the current value of the state (weather) and the function to update the state (setWeather). Compared to class-based components, where we would use this.state = { weather: 'sunny'} in the constructor, this hook simplifies the process.
import react, { useState } from ‘react’;
const VbComponent = () => {
const [weather, setWeather] = useState(‘Sunny’);
return(
<div>
<button onclick="”{()" ==""> setWeather(‘Raining’)}”>
update weather state
</button>
</div>
)
}
useEffect – Adding Side Effects to Your Component
The useEffect hook allows the addition of side effects to your component, akin to the lifecycle methods in class-based components. This hook can be employed to fetch data, register event handlers, and make changes to the DOM.
import React, { useEffect, useState } from 'react';
const VoorbeeldUseEffect = () => {
const [testState, setTestState] = useState([]);
useEffect(() => {
const helperFunctie = async () => {
const response = await fetch('https://eenwebsite/waar/de/content/staat/die/we/willen');
setTestState(response.data);
}
helperFunctie();
}, []);
return (
Some JSX
);
}