Introduction:
One of the most used react hook is useState()
, it lets you add a state variable to your function-based component. In this article, we'll dive deep into the useState()
hook, its syntax, and usage examples.
Explanation of useState() Hook:
The useState() hook takes an initial value (String, Number, Array, Object, etc)
as its argument and returns a pair of values: the current state and a function to update the state. This powerful hook enables functional components to have state management capabilities similar to class components.
Examples
In the above example JavaScript array destructuring
is used. It means that we’re making two new variables state and setState, The state variable holds the current value of the state, while setState is a function used to update the state.
To elaborate further, consider the equivalent code without array destructuring:
Explanation: When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it. Using [0] and [1] to access them is a bit confusing because they have a specific meanings. This is why we use array destructuring instead.
Function version of initialValue
When you have very slow and complex computation as an initialValue in state then it will take much time. So to solve this issue you can use the function version instead.
Output of above code:
Objects State:
In some cases, it is important to use object states as they can hold the collection of the same data.
const [style, setStyle] = useState({ color: 'red, fontSize: 20 })
While using object states, you have to keep one thing in mind when you try to change current state value using setState
function you have to use the spread operator (...
) to preserve the previous state otherwise you will lose the previous state.
Example:
Output of above code:
And the output of the above code without using the spread operator is a style return statement (Bad Practice)
Conclusion
In this article, we explored the useState() hook in React and learned how to utilize it effectively. We covered the syntax, usage examples, and best practices. By leveraging the useState() hook, you can handle state management efficiently in your function-based components. If you have any additional insights or questions, feel free to leave a comment. Let's continue exploring new concepts and inspiring each other in the world of JavaScript development.
Connect with me on Twitter, Linkedin and GitHub! to stay updated and join the discussion!
0 Comments