Hello, dear learner! Are you ready to delve into the world of React? Today, we'll explore the React state — data that a component manages and modifies. Think of a traffic light: its color (red, yellow, or green) is the state of the traffic light.
Our chief aim is to learn how to utilize useState and setState to manage the state in React components using hardcoded data. Excited? Let's begin!
In React, "state" refers to the data of a component that can be monitored and altered. Picture a simple counter: the count value is our state data. When someone clicks the increment button, the count changes, which triggers a re-render.
In this code snippet, our state variable count is declared and initialized with 0 using useState(0). When the button is clicked, the count increases, initiating a re-render of the component.
useState is a React hook that introduces state to functional components. useState is used to declare a state variable. It returns a pair: the current state value and a function to update it.
Let's declare a state variable color with an initial state:
Suppose we have a favoriteColor component that uses useState to manage hardcoded data:
FavoriteColor always displays "My favorite color is blue" — because favoriteColor is hardcoded as "blue".
