The term "hooks" can refer to different things depending on the context. Here are the most common meanings:
In Programming (especially React.js)
Hooks are functions that let you “hook into” React state and lifecycle features from function components.
- Example:
useState
,useEffect
,useContext
- Before hooks, these features were only available in class components.
- Introduced in React 16.8.
Example (React Hook - useState
):
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
useState
– What Is It?
In React, useState
is a hook that allows you to add state to a function component.
Think of it like this:
Before hooks, only class components could have state.
useState
brings state to function components.
Syntax
const [state, setState] = useState(initialValue);
-
state
→ current value -
setState
→ function to update the value -
initialValue
→ starting value of the state
Example: Counter
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // count starts at 0
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
How It Works
-
useState(0)
initializes the state with0
. -
count
holds the current value. -
setCount()
updates the value and re-renders the component.
Why Use useState
?
- Make dynamic UIs (like form inputs, toggles, counters, etc.)
- Trigger re-renders when data changes
- Avoid class components and use clean, functional code
Example: Input Field
function NameForm() {
const [name, setName] = useState('');
return (
<div>
<input
value={name}
onChange={e => setName(e.target.value)}
placeholder="Type your name"
/>
<p>Hello, {name}</p>
</div>
);
}
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.