Select Page

Category: state management

Build a state management system with vanilla JavaScript

Managing state is not a new thing in software, but it’s still relatively new for building software in JavaScript. Traditionally, we’d keep state within the DOM itself or even assign it to a global object in the window. Now though, we’re spoiled with choices for libraries and frameworks to help us with this. Libraries like Redux, MobX and Vuex make managing cross-component state almost trivial. This is great for an application’s resilience and it works really well with a state-first, reactive framework such as React or Vue. How do these libraries work though? What would it take to write...

Read More

Managing State in React With Unstated

As your application becomes more complex, the management of state can become tedious. A component’s state is meant to be self-contained, which makes sharing state across multiple components a headache. Redux is usually the go-to library to manage state in React, however, depending on how complex your application is, you might not need Redux. Unstated is an alternative that provides you with the functionality to manage state across multiple components with a Container class and Provider and Subscribe components. Let’s see Unstated in action by creating a simple counter and then look at a more advanced to-do application. Using Unstated to Create a Counter The code for the counter we’re making is available on GitHub: View Repo You can add Unstated to your application with Yarn: yarn add unstated Container The container extends Unstated’s Container class. It is to be used only for state management. This is where the initial state will be initialized and the call to setState() will happen. import { Container } from 'unstated' class CounterContainer extends Container { state = { count: 0 } increment = () => { this.setState({ count: this.state.count + 1 }) } decrement = () => { this.setState({ count: this.state.count - 1 }) } } export default CounterContainer So far, we’ve defined the Container (CounterContainer), set its starting state for count at the number zero and defined methods for adding and...

Read More

Understanding React `setState`

React components can, and often do, have state. State can be anything, but think of things like whether a user is logged in or not and displaying the correct username based on which account is active. Or an array of blog posts. Or if a modal is open or not and which tab within it is active. React components with state render UI based on that state. When the state of components changes, so does the component UI. That makes understanding when and how to change the state of your component important. At the end of this tutorial, you...

Read More
000webhost logo