Learn to use useState hook, this very minute!

Shivani Gupta
May 26 · 5 min read

React team introduced React Hooks in October 2018 and finally released in React v16. 8.0 in February 2019. In the next release i.e. React v17 React team did not add any new features for developers and focused on making it easier to upgrade React itself.

Source

Most of us have already started working on hooks or in the process of switching to React hooks slowly. We are using latest tech stack and React Hooks for most of the projects in InMobi. If you are curious to know what we are building at InMobi/glance or anything related to tech, feel free to ping me. useState is one of the most important and widely used Hooks while developing functional component in React. To put your curiosity at ease, I am going to show you few ways to use useState, this very minute! But before we jump onto usestate, there are few things you must be aware of for better understanding of useState. Let’s get started. 😄

What is State?
State stores component’s data and enables component to keep track of changes. A state can have business data, communication data to show error or success messages, control data like forms, session data related to user/user permission and location data like url path, history etc.
Use state only when data is dynamic and expected to be changed between renders.

What is Hook?
As we are moving from class based components to function based component, React Hooks helps us to use state in functional Components. We are not going to deep dive into Hooks. Let’s concentrate on useState.

What is useState?
useState allows us to add state to functional components. Start with importing useState Hook from React.

  • stateIdentifier: Access state with this identifier name in component.
  • updateStateFunction: This function allows you to update the state.
  • initialState: Assign initial state to state identifier. The initial value will be assigned only on the initial render.

✍️ You can use useState as many times as you want to create different states. Do you ever wonder why I am using const and not let? There is no restriction and you can use either let or const. I prefer const as I don’t want to share its name with a function or a variable in the same scope to mitigate error. You can follow the rules of const and let when declaring your state to determine if you should use let or const. Front tooling is very sophisticated and errors can be caught at development time with linters so you don’t have to worry if you have used same name by mistake.

1.Basic initialization: Each piece of state holds a single value, which can be an object, an array, a boolean, or any other type you can imagine. Let me show you few examples of useState.

2.Optional chaining : ES2020 introduced the optional chaining operator denoted by the question mark followed by a dot. The operator implicitly checks if the data is not null or undefined before attempting to access the data.User . If data.user is undefined, data.user.name fails with an error but data?.user?.name will return undefined. Pretty cool!😎

3. Spread operator: Spread operator can be used to copy properties from a provided object onto a new object. One use case of this feature could be to make default value assignments. We want to merge initial values and default value into one and create userDetails state.

4. Function: We can initialise the state by making use of function. Here I am going to call function getUserDetails to fetch initial value for user details through REST API and create new state userDetails. Notice that I am using arrow function to execute getUserDetails. We want the function to be executed only once at the time of initial render. Read more about it on blog by Kent.

5. Date Objects: We can initialize date state variable to the current date and time using Date object.

6. Object.keys: Let’s see an example of how to set radioVal state using Object.keys method.

7. Few more examples: We can set initial payload in payload state for pagination API and few more examples.

Source

Learning never ends for developers. Front End is one of the most complex environments to work when you have plenty of libraries and frameworks to learn for development, keeping up with frontend tooling, and the vast range of devices to support during development, it has gotten way bigger than imagined. 🌐

Thank you for reading this article. If you have enjoyed it, please feel free to click the 👏 button to help others find it .
References: http://jamesknelson.com/5-types-react-application-state/ , https://blog.logrocket.com/a-guide-to-usestate-in-react-ecb9952e406c/

Frontend Weekly

It's really hard to keep up with all the front-end…

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Shivani Gupta

Written by

I’m a Front-End Developer based in Bangalore, India. I believe in pretty designs and clean coding.

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store