DEV Community

React State Guides

React State allows us to manage changing data in an application.

This is a collection of top and trending guides written by the community on subjects related to React State concepts. For all things React, check out the React tag! Please contribute more posts like this to help your fellow developer in need.

Testing React Hook State Changes

Edit (2020): I would recommend switching over to react-testing-library, and changing your testing approach to test how your component changes with state rather than that state changed. While this approach works, it is not the ideal solution to the problem. I originally came up with this solution because I started React work using class components and being able to use the enzyme helpers to directly test my values of state against what I expected. With hooks, the testing approach has changed and that is no longer ideal. We should be testing our full component and how the component responds to the state change, not that state has changed.


How to pass state between components in reactjs

In this post, i'll explain how to pass a state between components in Reactjs.

We'll build a small 'How many books did you read?' app, in this application, we

have two main components one big called 'Library' and another small 'Book', we have 3 books in the library state and each book has its own state. check any book to count as read. try the app here


Update boolean state right with React Hooks

Creating a boolean state and a toggle method for it is a pretty common use case. The spinnet is 100% correct in terms of functionality. But it could be better in terms of performance. Let's see how it can be improved.


Accessing React State right after setting it

As I have been browsing Stack Overflow questions, I’ve noticed that many bugs are due to trying to access a state value after setting it.


An alternative to handle state in React: the URL !

Managing the global state of a React app is an endless war between libraries. Therefore, in order to add my 2 cents, we'll see how to do the exact same thing using the URL and react-router.


Updating react nested state properties

Working with react inevitable requires you to manage the state of your application at some point, bearest minimum the state of a component you're currently working with.


React hooks - working with state (array of objects)

Edit: I've also added how to edit/update the state using an input and a couple buttons. Found at the bottom of this post.


Global state management in React with global variables and hooks. State management doesn't have to be so hard.

First of all I'd like to talk a little bit about state management in react. State management in react can be divided into two parts


React Hooks: Lift up / pass down state using useContext and useReducer

I've ran into a situation where I had many child and sibling components trying to share the state between them. Earlier, I used prop to send a method to share the updated states between the components. At one point of time, the number of props kept increasing and I hated that.


Passing State to Components Rendered by React Router (and Other Fun Things)

But in React, passing state (or helper methods) is where all the power comes from -- it's what makes React so reactive. So you will want to use the first code snippet to get the functionality you want. The Route path in that code is using the render method to pass an inline function which will render the Homepage -- you may be wondering, why can't we just pass an inline function using the regular component method from snippet #2 and get the same result? The answer is that the component method will actually unmount and remount the entire component every time the state changes if you use an inline function with it. This creates an unnecessarily energy-expensive program when you could just use the neat render method that the friendly React devs intended you to use.


Persisting your React state in 9 lines

This article will take you through the process of creating a reusable custom hook that persists our state to local storage.


Sharing state using React's Context API

Global state in React is synonymous with libraries like Redux. If you ever needed to share state like the current route or data from an API with multiple components, then you may have reached for Redux yourself.


HOW TO PROPERLY SET INITIAL STATE IN REDUX

In Redux, all your application state is held in the store; which is an object that holds the complete state tree of your app. There is only one way to change its state and that is by dispatching actions.

Actions are objects that consist of a type and a payload property. They are created and dispatched by special functions called action creators.

see a small contrived and detailed example below:

First creating the Redux store:


You Can Definitely Use Global Variables To Manage Global State In React

React provides a very good and simple way to manage local states through state hooks but when it comes to global states the options available are overwhelming.


Synchronous State With React Hooks

Since I've converted my dev to React Hooks (rather than class-based components), I keep running head-first into the asynchronous nature of state updates. I don't honestly understand why this rarely seemed like a problem in my class-based components. But with functions/Hooks, I keep hitting this "roadblock". And unlike other articles I've written, this isn't my cocky declaration that I have solved ALL THE THINGS!!! Rather, I'd be thrilled if someone can show me an improvement on my proposed solution.




How to update object or array state in React

Ever tried to update object or array state directly in React?

I did that, the state of my component didn't change.

Destructuring the object/array was the solution.


Persist Redux State with redux-persist

When we refresh page in a web-app, the state always resets back to the initial values which in not a good thing when you try to build some large web-app like e-commerce.


What is the difference between State and props in ReactJs?

State - This is data maintained inside a component. It is local or owned by that specific component. The component itself will update the state using the setState function.


useContext for better state management!

Managing data in an app is little tricky when many components are sharing and updating it. useState, useReducer, useMemo etc. are some state management hooks in React, which are very efficient and have their own ways to work in different scenarios. Though all these hooks are effective, there are still some situations where managing state becomes difficult.


Global state management with react hooks and context

From prop drilling to centralized global state management with react


Setting state for parent from within useEffect hook in child component causes an infinite loop

That's exactly what I have found recently.

Let's say we have a parent and a child and we pass setState function to the child in order to it can set state for parent from within a useEffect hook inside child component. This scenario will cause an infinite loop no matter what you put in the dependencies' second argument array of useEffect hook.

Let's say what in my opinion happens. setState causes the parent to re-render because we are updating its state. But this implies a render of the child. And I say render and not re-render because when parent re-renders, for useEffect hook is like rendering of the child was first render, and that's why no matter what you put on the dependencies array it will always execute its side effect, setting state for parent and initiating a new loop, that will continue forever.

So when you lift the state up in React.js you must take care not to call setState or dispatch (this applies as well to useReducer) inside a useEffect hook from within a child component.

Here, I show you the code:


React doesn't need state management tool, I said

But context API usually brings performance problems and is also a bit awkward to use it properly, so today I'll try to show how to avoid common problems, and also build your own (micro) state management tool, without any compromises.


Next.js persistent state with React hooks and localStorage. How to make it work?

I'm trying to create persistent state with localStorage and React hooks in Next.js SSR app and everything seems to look good but when I reload page after update my data I'm getting error:


How State Management works? Dead simple SM in Vanilla JavaScript

Dead simple State Management in Vanilla JavaScript

It's been years now since you started using Redux, MobX or even plain React Hooks and have no idea how state management works and why it works the way it works? I'll show you the dead simple bottom level of work in state management sans any optimization or other bells and whistles.


Recoil vs Redux | The Ultimate React State Management Face-Off

React with its component-based approach has made the life of developers easy by managing separate state and logic for each component and the ability to re-use them when required. But what if you wanted to use a shared state between multiple components or maybe fetch data from an API once and make it available to all the components in your app? That’s when global state management libraries like Redux, MobX, etc., come into play.


What is the standard way to keep UI state and backend state synced during updates? (React and Node)

When user updates the card, I send a PUT or POST request to the backend,

which updates the card details (with or without DB doesnt matter, just assume backend state is updated). good.


How to: mobx-state-tree + react + typescript

This is a walkthrough on how to get a full setup with mobx-state-tree and react in a CRA app with typescript. This guide doesn't focus too much on the theory or how things work under the hood and mostly includes practical examples (code!) on how to make things work.


Managing React State with Zustand

A small, fast and scalable bearbones state-management solution using simplified flux principles. Has a comfy api based on hooks, isn't boilerplatey or opinionated.


React Router - Using Location State for Custom UI Navigation

Now that we have this state being inserted into our location object, where does the actual magic happen? It all happens on the back button. Let's say we want to have special text when we are coming directly from the blog roll vs. any other page:


Custom Navigation Drawer and Sharing State From Drawer (with useContext)



React Navigation Custom Navigation Drawer and Sharing State (with useContext)


How to syncing React state across multiple tabs with useState Hook and localStorage

With the increasing complexity of frontend applications in recent years, some challenges to maintaining user experience with the products we build are emerging all the time. It's not difficult to find users who keep multiple instances of the same application opened in more than one tab in their browsers, and synchronizing the application's state in this scenario can be tricky.


Getting started with React Query - Easy server state management in React

So the useQuery in here doesn't differ much from the one in Home.js. It adds the id to the identifier, so each post has its own state. Additionally, I've added a timeout for 1 second to the getPost function to make the loading state more visible. Also, I've appended a random string to the title to make the re-fetching visible.


Sharing state like Redux with React's Context API

In learning React, one of the first challenges I faced was figuring out state management. State is a vital part of any application that has more complexity than a simple blog or brochure site. React has a fantastic toolset to manage component level state both in the case of functional components with hooks, and class based components. However global state is a bit of a different story.


React Tutorial: Change State with React Hooks and Mouse Events

The main focus of this tutorial is about how to change state with React Hooks and mouse events, so to save you some time I went ahead and created a Codesandbox project that you can fork with the basic Card component completed.


Why you should use MobX State Tree in your next React project

At Lloyds we write a lot of React and React Native apps. All apps require some state management, so we naturally had to choose a state management library to use in our projects. After some consideration and testing, some back and forth with Redux, MobX and some other solutions, we decided to try MobX State Tree. We loved the features, simplicity and developer experience so much! We just had to share it, so we decided to write this article.


Hooks to persist state in the query string or history.state in React

Good URLs enable users to keep a reference to web applications in a specific state or to share them with other people. While the path of the URL usually defines the page the user is on, eg. a search results page (/search), the query string is often used to encode a custom state of that page, eg. a search query for "shoes" with a set of filters for colors and size (/search?q=shoes&color=blue&color=black&size=44). A user could now bookmark this URL to come back later or share it with a friend or click on one of the products to check it out in detail, and if they want to return to the results page, they could just use the back functionality to go back to the same search results and select another product.


Incrementing State In Functional Components

I appreciate the concision of this approach, though just to be explicit, it works the same as the following by not reassigning a state variable within setState (which React tends to complain about).


React State Management: When To Use Redux And What Are The Alternatives

When writing applications with react you will soon reach a point where you pass down callback functions as props two or three levels, to change the parents state. For most projects you will need a third party solution for global state management, so you can directly access and modify state from any component in your app, without passing callbacks down the DOM.


Handling image loading and error state in Next.js

When a web application displays many images, it is a good idea to give immediate feedback to the user of what is happening. One way to address this is to use an alternate image to show the current state of an image.


A React hook to handle state with dependencies

While building the app, I created something I call a "dependent state" custom hook. It's useful when you have a piece of state with a range of valid values that are calculated based on one or more dependencies. If a dependency changes, the state's current value may no longer be valid, and will need to be checked and possibly reset.


Use Zustand and Immer to Manage the state of your React app

In this example I will use Inner.js with Zustand, however you can use it with many other state managers. I believe that after using Inner.js, you won't want anything else to work with objects and arrays in your state.


React Hooks: Creating Custom State Hook

The state and logic of the counter are now encapsulated into the function. It should return the counter and handlers, responsible for state modifications. Also do not forget to export the function.

In a current example, the function returns an object with state values, but it is not restricted only to objects. As it is only a simple JavaScript function, we can return any data type. It could be aswell an array:


Recoil - The Asynchronous way to manage state [ Part 1 ]

In previous post we got an overview of some Recoil terminologies and how to manage state using it.


ES6 Generators for State Management in React

When we talk about state management in JavaScript, we’re usually talking about using framework-specific libraries or tools, like redux or setState in React. But as we are looking for a state management strategy, I think there are powerful tools at our disposal in ES6. If we are implementing sequential state updates (multi-step forms, carousels, animations, etc), one such tool is a generator.


Implementing State Management using Context API and Hooks in React

With React's release of production-grade features such as Context API and Hooks, developers can already implement global state management without having to use external libraries (e.g. Redux, Flux, MobX, etc.) for the same purpose.


Can React state management get any simpler than this?

I'm one that loves simplicity in things. So despite the plethora of state management libraries for React, I have always wondered what the absolute "simplest" approach would be.


useStateWithPromise: a custom hook to await state updates of useState

The general problem is that we want to wait for a state update an then do something afterwards. Unfortunatly we can not write sequential code, because every state update is asynchronous.

In "old" react we could simply pass a callback. As an example we will look at a class component, that contains filters for an article list view:


How to use same state for multiple controlled components in react hooks

In React class component we can use same event handlers to update state for multiple controlled components using event.target.name


Happy React State coding!