Mark As Completed Discussion

React Hooks

React Hooks are a new addition in React 16.8 that allow you to use state and other React features without using class components. Hooks are functions that let you 'hook into' React state and lifecycle features from function components.

One of the most commonly used hooks is the useState hook. It allows you to add state to your functional components. Let's take a look at an example:

SNIPPET
1import React, { useState } from 'react';
2
3function Counter() {
4  const [count, setCount] = useState(0);
5
6  function increment() {
7    setCount(prevCount => prevCount + 1);
8  }
9
10  return (
11    <div>
12      <h2>Count: {count}</h2>
13      <button onClick={increment}>Increment</button>
14    </div>
15  );
16}
17
18export default Counter;

In this example, we're using the useState hook to add a state variable count and a function setCount that allows us to update the value of count. The initial value of count is set to 0.

Whenever the button is clicked, the increment function is called which updates the value of count by incrementing it by 1. The updated value is then displayed in the h2 tag.

React Hooks allow you to easily manage state and perform side effects in functional components, making them a powerful tool for building React applications.

By using hooks, you can write more concise and readable code compared to class components, as you no longer need to deal with the complexities of the this keyword and lifecycle methods.

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