Back to results for “Hooks”
React › Hooks

What does the useState hook do, and how do you use it?

Beginner

Answer

useState lets a function component remember a value between renders and gives you a function to update that value. Calling the update function tells React to re render the component with the new value.
function LikeButton() {
  const [liked, setLiked] = useState(false);
  return (
    <button onClick={() => setLiked(!liked)}>
      {liked ? 'Liked' : 'Like'}
    </button>
  );
}
Real-world example A social media post's like button remembers whether the current user has already liked it, using useState to toggle between a liked and unliked appearance whenever the button is clicked.

Common follow-ups: Why does calling the state setter not immediately change the value inside the current render?;Can you store an object or an array inside useState?