Lesson 5 - Hooks

5.1 - Hooks Fundamentals

React Hooks are functions that enable you to use state and lifecycle features from within functional components. They were introduced in React 16.8, providing a more direct and intuitive way to work with stateful logic in functional components. Hooks aim to simplify React code by making it more readable, maintainable, and reusable.

Imagine a language selector in your web application. When the user changes the language, the hook will automatically detect the change and instruct its host component to reflect the update by re-rendering.

The useState and userEffect are the two most used hooks in React. Let's take a quick overview of them with examples.

useState: The useState hook allows you to update and manage the state of functional components. It returns an array with two elements: the current value of the state and a function to update the value of the state.

Like in our example below, we declared a state count with an initial value of 0. Here, the setCount is the function to update the value of count.

import React, { useState }  from 'react';

function App() {
 const [count, setCount] = useState(0);

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

The above example will update the value of count each time the button clicked.

useEffect: The useEffect hook allows you to perform side effects in your components. These side effects can be fetching data, timars, updating DOM, and many more. It runs every time the page content is updated.

For example, if you have a timer in your application. The userEffect hook will render the timer component for each second.

Let's take a look at a basic example of useEffect hook.

import React, { useState, useEffect }  from 'react';

function App() {
 const [count, setCount] = useState(0);

 useEffect(() => {
 document.title = `You clicked ${count} times`;
 });

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

Here, the page title will be updated via useEffect every time the page renders with the updated value of count.

We'll discuss useEffect briefly later in this course.

Why do we need hooks, and what are the benefits of using hooks? Hooks provide several benefits that allow functional components to become more powerful and flexible.

Simpler Code: Hooks eliminate the use of class components, making it easier to understand and maintain code. Functional components with hooks are generally shorter and easier to read.   Reusable Logic: Hooks allow you to reuse stateful logic across multiple components without changing the component hierarchy. It enables you to extract and share logic between components.   Better Performance: Hooks improve the performance by minimizing the number of re-renders and updates.

Our next move towards defining custom hooks. Let's begin.