What Are React Hooks?
React Hooks are functions that let you use React features (like state and lifecycle methods) in functional components. They enable cleaner, simpler, and more readable code.
Why Were Hooks Introduced?
React Hooks solve several issues present with class components:
Complexity of Classes:
Managing lifecycle and state with this in class components was often error-prone. Hooks simplify this.Logic Reusability:
Hooks make it easier to reuse logic across components without using HOCs or render props.Improved Code Readability:
Hooks streamline component code, making it shorter and easier to understand.Incremental Adoption:
Hooks can be used alongside class components, allowing gradual migration.
UseState
UseState is a Hook that allows you to add state to functional Components.
State means data that can change over time (like User input, button clicks or API data).
UseState returns two things:
- The Current State Value
- A function to update that Value
UseState is a React hook that lets us add and manage state inside functional components. It returns a State Variable and a function to update it.
For example:
We can track a Counter Value using const
[count
, setCount
] = UseState(0) and update it with setCount
when the User click a button.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state
return (
<div>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Top comments (0)