Introduction :-
React is a popular javascript library for building user interfaces, and its introduction to hooks in 16.8 brought significant improvements to functional component. One of the most widely used hooks is useState , which allows developers to add state managment capabilities to their functional compoenents. In this blog post, we will explore the usestate hook, understand its usage, and learn how it simplifies state managment in React applications.
Why useState? :-
Before the introduction of hooks, state managment in React is primarily done using class components. While class components serve the purpose , they often require boilerplate code and complex syntax . Functinal components, on the other hand, were simpler and more lightweight but lacked built in state managment capabilities. The useState hook bridges this gap by enabling functinal components to handle state, making them more powerful and easier to work with.
The useState hook is a function that takes an initial state value as its arguments and return an array with two elements: the current state value and a function to update that state value.
1const [state, setState] = useState(initialState);
Here's the breakdown of syntax :-
state = Represents the current value of the state variable. It can be of any data type e.g = Boolean, String, Object or Array.
setState = The function return by useState that allows you to update the state value . When called with a new value, it triggers a re-render of the component , updating the state and any component elements that depend on it.
useState(initialState) = the useState function takes the initial state values as its argument . This initial state is only used during the first render of the component. After that, the state variable will be updated with new values.
🙏 Dhanyawaad