this.state - How to Use State in React js (2023)

Tim Smith
  • Home
  • Blog

If you’re anything like me, the concept of state was confusing at first. In this tutorial, we’ll learn how to use state and props in a react js application.

How is state set? Why use that if props can handle data? In this post, we’re going to answer those questions and more.

Props are pieces of data passed into a child component from the parent while state is data controlled within a component

State vs Props in React js

Props and state both have their place within react. There are instances where each one is appropriate and I can’t imagine trying to build things in react without both. Before we get too far into it, I’ll explain so here’s the skinny: Props are pieces of data passed into a child component from the parent while state is data controlled within a component. The example below demonstrates how we pass a prop into a component:

// app.js<App prop='Some data for a prop' />

Many times state will be used to pass data into a child component via props. There are even ways to manipulate a parent component’s state from a child component. By the end of this post, you’ll know how to do both.

State Management in a React js Component

Before we can get into the details about creating a state within our component, it’s important to note that state can only becreated in a class component. The reason for this is the fact that our state will be housed in a class constructor.

What’s a constructor you say?A constructor is a concept involved in object-oriented programming which creates an object. This is where we want to set up our state for the component. It should also be noted that a constructor is not necessary for class components to receive props so if we aren’t “doing” anything in our constructor then we don’t need to have one.

(Video) Full React Tutorial #8 - Using State (useState hook)

If you aren’t sure how to create a component, you canlearn about that here. Now, on to the code…

The code below shows how to set up an empty constuctor. This should not be something we’re putting into production code as we only want to use constructors if they are actually doing something. A constructor isn’t needed for a class component to receive props, so unless you have state or have to bind a function you probably won’t need it.

// app.jsimport React, { Component} from 'react';class Example extends Component { constructor(props) { super(props); } render() { return ( ... ) }}

Adding our state object is easy enough. Inside the constructor, aftersuper(props);, just addthis.stateand set it equal to an empty object. Once we have created the empty object, we can fill it with data of whatever key and value pair we’d like. The example below has 3 different pieces of data: a boolean, a string, and a number.

// app.jsimport React, { Component} from 'react';class Example extends Component { constructor(props) { super(props); this.state = { isHungry: true, topping: "Pepperoni", slices: 8 } } render() { return ( ... ) }}

In the Pizza component above, you can see that we have a state which includes a boolean value of true forisHungry, a string value of “Pepperoni” for thetopping, and the integer 8 for the number ofslices. We can actually use any data type within state such as bool, integer, string, array, or object.

I know what you’re thinking.Super Cool, Tim. Now what?

I’m glad you asked. That brings us to the next section:

Accessing State from the Render Method

Using state inside of our render method is pretty easy. LikeSUPEReasy. Can you guess how to do it without me telling you? I’ll give you a few minutes.

Did you get it? I’ll go over it anyway just in case. Let’s say we just want to output the topping for our pizza. We could do that in a paragraph tag like so:

// app.js<p>{this.state.topping}</p>

The code above would be output in the browser like this:

(Video) Learn to use State in React in 19 minutes (for beginners)

<p>Pepperoni</p>

How do we change the state?

Okay, so we have our state and we can output it. It’s basically the same as props but more work, right? Wrong. This next section is the part that really makes state different from props. That difference is the ability to change the state within a component. Below is some code that explains how to do this:

// app.jsthis.setState({ item: 'newValue' });

The code above calls athis.setStatefunction and passes in an object with key-value pairs. If the key matches one we already have in state, it updates the value in state to the new value provided. If the key doesn’t exist in state, it will be created with the given value.

How about we add a function to our Pizza component where we subtract a slice from our total slices. Below is the code to do this, which could then be triggered by a button click or other action.

// app.jsimport React, { Component} from 'react';class Example extends Component { constructor(props) { super(props); this.state = { isHungry: true, topping: "Pepperoni", slices: 8 } this.eatSlice = this.eatSlice.bind(this); } eatSlice() { const totalSlices = this.state.slices - 1; this.setState({ slices: totalSlices }); } render() { return ( ... ) }}

If we assume this function will be fired when a button is clicked, then each time the user clicks that button our slices in state will go down by one (even into negatives because we have not created logic to prevent that). Each time the state changes from the button click, our component will re-render with the new data.

This allows users to modify data on a page in real time, which is awesome. We can also pass our state into a child component as props. This brings us to our next topic which is changing parent state from a child component.

Changing Parent State from Child Component

For the sake of demonstration, let’s create a component calledButton. Our new component will allow us to provide a few props and have it spit out a button to render differently each time it’s called.

Our newButtoncomponent will not have any state of it’s own and will not use any lifecycle methods, so it will work as a stateless functional component. The two props we want to pass in will beactionandlabel.

Here is the code for our newly createdButtoncomponent:

(Video) Learn useState In 15 Minutes - React Hooks Explained

// app.jsconst Button = ({ action, label }) => ( <button onClick={() => action()}>{label}</button>);

Pretty simple, right? We will use ouractionprop to pass in a function, and ourlabelprop to pass in a string which will set the text on the button. Since we’re passing in a function prop, we can just use the function we already wrote to eat a slice of pizza. I’ll show you how this will work within the render function:

// app.js...render() { return ( <div> <Button action={this.eatSlice} label="Eat a slice" /> </div> )}...

What fun is it to run out of pizza? How about we add another button to buy another slice so we don’t ever have to run out? Since we created a button component which can already take a function and label, we can simply reuse the component and pass in new values for those props.

Before we drop in our component, we need to write thebuySlicefunction. The code below should do it. The way it works is exactly the same as theeatSlicefunction except that it will add 1 instead of subtracting 1, then settingthis.state.slicesto the new value.

Here is the code for the functionbuySlice:

// app.js...buySlice() { const totalSlices = this.state.slices + 1; this.setState({ slices: totalSlices });}...

We need to remember to bindthisto our function in the constructor as well. Right now our Pizza component should look like this:

// app.jsimport React, { Component } from 'react';class Example extends Component { constructor(props) { super(props); this.state = { isHungry: true, topping: 'Pepperoni', slices: 8, }; this.eatSlice = this.eatSlice.bind(this); this.buySlice = this.buySlice.bind(this); } eatSlice() { const totalSlices = this.state.slices - 1; this.setState({ slices: totalSlices, }); } buySlice() { const totalSlices = this.state.slices + 1; this.setState({ slices: totalSlices, }); } render() { return ( <div> <Button action={this.eatSlice} label='Eat a slice' /> </div> ); }}

Since we have our function to control the state in the parent component and we have boundthisto the function, we are ready to pass it into the child component and let the child component call thebuySlicefunction.

Let’s create a new button to buy a slice of pizza. Modify your render method in the Pizza component to look like this:

// app.js...render() { return ( <div> <p>Slices Left: {this.state.slices}</p> <Button action={this.eatSlice} label="Eat a slice" /> <Button action={this.buySlice} label="Buy a slice" /> </div> )}...

Just to make it a bit easier to see what’s going on, I have added some text which will show you the current number of slices available. We can now click our “Eat a slice” button to reduce the number of slices by one and we can click the “Buy a slice” button to increase the number of slices by one.

Conclusion

Working with state is an essential skill to have in react js. It makes our lives as developers easier and more managable without overcomplicating things. It also makes it possible to have extremely dynamic and fluid user experiences quickly.

(Video) React Tutorial 40 - React Hooks | useState() | Using the State Hook

In this post, we talked about what state is, how to create state, how to change state, and how to manipulate state from a child component. This should be enough information for us to control the data within our components in most cases. Now go forth and build cool stuff!

#react

this.state - How to Use State in React js (1)

Tim Smith

I build things using React, Node, PHP, and more. Currently, I’m a Software Engineer working on D&D Beyond at Wizards of the Coast. You can follow me on Twitter at @iam_timsmith.

FAQs

What is the purpose of use state in React? ›

What is useState() in React ? The useState() is a Hook that allows you to have state variables in functional components . so basically useState is the ability to encapsulate local state in a functional component.

Can we use this state in setState? ›

setState() is executed, this. state inside it will always refer to the old state, and its value will be changed to the new state only after setState has finished executing, not while it is executing.

Why my useState is not updating immediately? ›

The “useState” set method is asynchronous; hence, the updates are not reflected immediately. However, this is not the reason for the change not getting reflected immediately in the method. Hence, all you need to do is to go for any of the methods which reflect the changes in the “useState” set method immediately.

How to set value using useState? ›

If you want to set an initial value for the variable, pass the initial value as an argument to the useState function. When React first runs your component, useState will return the two-element array as usual but will assign the initial value to the first element of the array, as shown in figure 5.

Is this state a keyword in React? ›

State is simply a property inside React.

Why do we use state instead of variable? ›

Use a state variable when a component needs to “remember” some information between renders. State variables are declared by calling the useState Hook. Hooks are special functions that start with use. They let you “hook into” React features like state.

Is state necessary in React? ›

React state has a very important relationship with rendering components. Whenever we return JSX from a React component, when that component is used, it will be rendered and therefore displayed in our application.

Do you know the 5 types of states in React? ›

Therefore, this article will clearly discuss the types of states such as Logical, Server, Form, Navigation, and Browser and the main ways to handle them. Also, it will help 25.12% of the developers who would like to learn React in the future.

Can I call this setState In render? ›

You can call setState() immediately in componentDidMount() and triggers an extra rendering, but this happens before the browser updates the screen, calling render() twice.

Can you await this setState? ›

No this. setState doesn't return a promise. So you can't use await in this case.

When should I pass this setState? ›

If you know you're going to use setState to update your component and you know you're going to need the current state or the current props of your component to calculate the next state, passing in a function as the first parameter of this. setState instead of an object is the recommended solution.

What can I use instead of useState? ›

An alternative to the useState Hook, useReducer helps you manage complex state logic in React applications.

Does useState always re-render? ›

useState() Hook is widely used in React applications to re-render the components on state changes. However, there are scenarios where we need to track state changes without re-rendering the components.

Does useState run every render? ›

At this point, we know that every time the useState value changes, it will call the render function which is the Component function itself.

What does useState () returns? ›

useState accepts an initial state and returns two values: The current state. A function that updates the state.

Can you call a function in useState? ›

As stated previously, useState enables you to add state to function components. Calling React. useState inside a function component generates a single piece of state associated with that component. Whereas the state in a class is always an object, with Hooks, the state can be any type.

What is the output of useState () hook? ›

useState() hook allows one to declare a state variable inside a function. It should be noted that one use of useState() can only be used to declare one state variable. Example: Program to demonstrate the basic use of useState() hook.

Is useState and this state the same? ›

useState , this. state and PureComponent are different terms and need not be confused together. As you understand useState is a way of handling state in a functional component whereas you use this. state for a class component.

What is state in React for dummies? ›

What Is 'State' in ReactJS? The state is a built-in React object that is used to contain data or information about the component. A component's state can change over time; whenever it changes, the component re-renders.

Can a state be a function React? ›

Show activity on this post. Yes you can.

Can you update state directly in React? ›

State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass.

How do you initialize a state in React? ›

Initializing state

In class components, there are two ways to initialize state — in a constructor function or as a Class property. Constructor functions, introduced in ES6, is the first function called in a class when it is first instantiated — meaning when a new object is created from the class.

When should I use useState? ›

Important things to know when using useState() hook

ONLY call useState() hooks inside a functional component: Hooks are created for functional components and should only be used in functional components. They don't work in class components. If you need to use state in the class component, then use the state object.

Do React hooks replace state? ›

Hooks are a more direct way to use the React features you already know — such as state, lifecycle, context, and refs. They don't fundamentally change how React works, and your knowledge of components, props, and top-down data flow is just as relevant.

Can we use state without constructor in React? ›

Initialize State Without Constructor

Another way of initializing state in React is to use the Class property. Once the class is instantiated in the memory all the properties of the class are created so that we can read these properties in the render function. Here is an example.

Why we should never update React state directly? ›

The state of a component is managed internally by React. Updating the state of a component directly can have unintended consequences that can be difficult to debug. If the state is updated directly as in the example above, the component will not rerender since the state is compared shallowly.

What are the 3 dots in React? ›

These three dots are called the spread syntax or spread operator. The spread syntax is a feature of ES6, and it's also used in React. Spread syntax allows you to deconstruct an array or object into separate variables.

How do you manage state? ›

When the state object changes, the component will re-render itself. React state management is basically half of a React app.
...
How to Manage State in React
  1. useState.
  2. useReducer.
  3. useMemo & useCallback.
  4. useEffect.
  5. useRef.
  6. Context and Custom Hooks.
  7. React Query & React Location.
  8. Zustand.
Nov 15, 2022

Can we use multiple state in React? ›

Multiple state updates within async methods e.g. fetch() weren't batched. However with React 18, all state updates occurring together are automatically batched into a single render. This means it is okay to split the state into as many separate variables as you like.

Does setState work immediately? ›

React hooks are now preferred for state management. Calling setState multiple times in one function can lead to unpredicted behavior read more.

Does setState take a callback? ›

The setState function takes an optional callback parameter that can be used to make updates after the state is changed. This function will get called once the state has been updated, and the callback will receive the updated value of the state.

Does useState trigger a rerender? ›

useState returns an array with exactly two values: The current state. During the first render, it will match the initialState you have passed. The set function that lets you update the state to a different value and trigger a re-render.

What is the difference between setState () and replaceState () methods? ›

With setState the current and previous states are merged. With replaceState , it throws out the current state, and replaces it with only what you provide. Usually setState is used unless you really need to remove keys for some reason; but setting them to false/null is usually a more explicit tactic.

Is useState synchronous or asynchronous? ›

useState is an asynchronous hook, it will wait for the component to finish its cycle, re-render, and then it will update the state.

Can you call setState multiple times? ›

React will call that function with state and props, and use the result for next state. It is safe to call setState with a function multiple times.

Is setState always asynchronous? ›

This function is used to update the state of a component, but it's important to remember that setState is asynchronous.

What is the difference between this state and this setState? ›

setState() does not immediately mutate this. state but creates a pending state transition. Accessing this. state after calling this method can potentially return the existing value.

Why we should not update the state directly and use setState? ›

If you try to update state directly then it won't re-render the component.

Should I use useState or useEffect? ›

The useState hook is used for storing variables that are part of your application's state and will change as the user interacts with your website. The useEffect hook allows components to react to lifecycle events such as mounting to the DOM, re-rendering, and unmounting.

Should I use Redux or useState? ›

You should use local state i.e. useState as much as possible. Redux state should be the last resort. Only use Redux state if you absolutely need to pass data from one end of the application all the way to another end. This is both good practice for tight coupling and good performance.

Can you use useState twice? ›

If there are more than one state variable you want to monitor, it's simple enough to add a second or third useState hook.

Can useState hold an object? ›

One of React's most commonly used Hooks is useState , which manages states in React projects as well as objects' states. With an object, however, we can't update it directly or the component won't rerender.

Can I store function in useState? ›

The useState() is a Hook that allows you to have state variables in functional components. useState() is used to store/update data in function component and use it wherever required on the same component.

Does useState trigger useEffect? ›

By default, useEffect always runs after render has run. This means if you don't include a dependency array when using useEffect to fetch data, and use useState to display it, you will always trigger another render after useEffect runs. Unless you provide useEffect a dependency array.

Does useState need an initial value? ›

With the useState hook, you can pass a function as an argument to initialize the state lazily. As discussed, the initial value is needed only once at the first render. There is no point in performing this heavy computation on the subsequent renders. const [counter, setCounter] = useState(() => Math.

What happens if you don't use useEffect? ›

If omitted, the effect will run after each render. You can pass an empty array if you only want the effect to run on the first render. Dependencies can be states or props. Note that values defined inside a component outside of useEffect must be passed as dependencies when used inside useEffect.

How do you access the state of a component in React? ›

In React we can access the child's state using Refs. we will assign a Refs for the child component in the parent component. then using Refs we can access the child's state. Creating Refs Refs are created using React.

How do I check my state in React? ›

To declare state using React Hooks, we need to use the useState hook. The useState hook accepts a parameter which is the initial value of the state. In class-based components, state is always an object.

How to use state in JavaScript? ›

How does it work?
  1. First, we create an object which will represent our data's starting state.
  2. Next, we create our components that return a template string.
  3. Now, for the changes to update in our DOM we create a render function.
  4. We create a function that updates the current number when we click on the increment button.
Dec 7, 2021

How do you pass state value in react JS? ›

Passing State to a Component

To pass the state into another component, you can pass it as a prop. Then, inside <ExampleComponent /> , you can access the data as this. props.

How do you access the state in a function component? ›

useState is a Hook (function) that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.

How do I access state from props? ›

Component { state = { description: '' } constructor (props) => { const { description } = props; this. state = {description}; } render () { const {state: { description }} = this; return ( <input type="text" value={description} /> ); } } export default SecondComponent; Update: I changed setState() to this.

How do I get a component state? ›

You may access the child state by passing a callback to the child component. Now if you click the button in the child component, you will execute the function passed from the parent and have access to the child component's state variables.

How do I update this state in React? ›

The steps are discussed below.
  1. Go inside the App. ...
  2. At the top of the App. ...
  3. Create a Class based component named 'App'. ...
  4. Create a state object named text, using this. ...
  5. Create another method inside the class and update the state of the component using 'this.
Sep 27, 2021

Videos

1. UseState Tutorial For Beginners - React States Tutorial
(PedroTech)
2. React useState Hook & setState Explained - Reactjs State Tutorial
(Cem Eygi Media)
3. How To Use and Not Use State (React State Series 2/3)
(React Training)
4. ReactJS Tutorial - 11 - setState
(Codevolution)
5. React tutorial for beginners #11 State with functional component
(Code Step By Step)
6. React for Beginners #5 - State & useState
(Tech With Tim)
Top Articles
Latest Posts
Article information

Author: Jonah Leffler

Last Updated: 03/28/2023

Views: 5445

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.