Mark As Completed Discussion

React Hooks

React Hooks are functions that allow you to use state and other React features in functional components. They provide a way to manage state and side effects without writing class components.

Introduction to Hooks

In React, state and lifecycle methods were only available to class components. However, with the introduction of React Hooks in version 16.8, functional components can now have state and lifecycle capabilities.

useState Hook

The useState hook is used to add state to a functional component. It takes an initial value as an argument and returns an array with two elements: the current state value and a function to update the state value.

Here's an example of using the useState hook to create a counter:

SNIPPET
1import React, { useState } from 'react';
2
3function Counter() {
4  const [count, setCount] = useState(0);
5
6  return (
7    <div>
8      <p>Count: {count}</p>
9      <button onClick={() => setCount(count + 1)}>Increment</button>
10    </div>
11  );
12}

In the above example, the count variable represents the current state value, and the setCount function is used to update the state value. The current state value is displayed in the JSX code.

useEffect Hook

The useEffect hook is used to perform side effects in functional components. It takes a function as an argument and executes that function after the component has rendered.

Here's an example of using the useEffect hook to update the document title when the count state changes:

SNIPPET
1import React, { useState, useEffect } from 'react';
2
3function Counter() {
4  const [count, setCount] = useState(0);
5
6  useEffect(() => {
7    document.title = `Count: ${count}`;
8  }, [count]);
9
10  return (
11    <div>
12      <p>Count: {count}</p>
13      <button onClick={() => setCount(count + 1)}>Increment</button>
14    </div>
15  );
16}

In the above example, the useEffect hook is used to define a function that updates the document title with the current count value. The second argument of the useEffect hook is an array of dependencies, in this case [count], which indicates that the effect should only run if the count value changes.

Hooks provide a simple and concise way to handle state and side effects in functional components. They have greatly simplified React development and are widely used in modern React applications.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment