React's useState hook is a powerful tool that allows you to add state to your functional components. It allows you to manage and update state in your component without the need for a class component.
To use the useState hook, you need to import it from the 'react' library at the top of your component. Then, you can call the useState function and pass in the initial state as an argument.
For example, if you wanted to create a counter component that starts at 0, you would write:
In this example, the useState hook returns an array with two elements: the current state (count) and a function to update it (setCount). We can then use these elements in our component to display the current count and to increment or decrement the count when a button is clicked.
It's important to note that the setCount function should always be used to update the state, as it ensures that the component re-renders with the updated state. Additionally, React will only re-render the component if the state has actually changed.
Overall, the useState hook is a great way to add state to your functional components in a simple and efficient way. With a little practice, you'll be able to use it in a variety of situations to manage state in your React applications.