useState is a React Hook that lets you add a state variable to your component.
useState simple counter example
import { useState } from "react";
function CounterPage() {
const [count, setCount] = useState(0);
const decrementCount = () => {
setCount((prevCount) => prevCount - 1);
};
const incrementCount = () => {
setCount((prevCount) => prevCount + 1);
};
return (
<section className="counter-page">
<p>Count: {count}</p>
<button onClick={decrementCount}>Decrement</button>
<button onClick={incrementCount}>Increment</button>
</section>
);
}
export default CounterPage;
We cannot use short version because it accesses old count value.
So this code would increase counter only once.
setCount(count + 1); setCount(count + 1);
PostList example:
const PostList = ({ posts }) => {
return (
<div>
{posts.map((post, index) => (
<div key={index}>
<h3>{post.title}</h3>
<div>{post.body}</div>
</div>
))}
</div>
);
};
export default PostList;
// Usage
import { useState, useEffect } from 'react';
import axios from 'axios';
const App = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get('https://site.com/posts')
.then(response => {
setPosts(response.data);
setLoading(false);
})
.catch(error => {
console.error('Error:', error);
setLoading(false);
});
/*fetch('https://site.com/posts')
.then(response => response.json())
.then(data => setPosts(data))
.catch(error => console.error(error));*/
}, []);
return (
<div>{loading ? <p>Loading...</p> : <PostList posts={posts} />}</div>
);
};
export default App;