npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

setstate

v1.0.2

Published

Set local state in a React.Component

Downloads

11

Readme

setstate

Set local state in a React.Component

setstate on github

Installation

yarn add react setstate

Example

setState keeps local state on an instance of React.Component or React.PureComponent.

In practice, it looks like so:

import React from "react";
import setState from "setstate";

class Counter extends React.Component {
  constructor() {
    super();
    this.state = { count: 0 };
  }

  render() {
    return (
      <div>
        <h1>{this.state.count}</h1>

        <button
          type="button"
          onClick={() => this.setState(({ count }) => ({ count: count + 1 }))}
        >+</button>

        <button
          type="button"
          onClick={() => this.setState(({ count }) => ({ count: count - 1 }))}
        >+</button>
      </div>
    );
  }
}

Use in Create React App

create-react-app ships with transform-class-properties installed.

This can make working with local state faster and less ceremonious.

class Counter extends React.Component {
  // don't mess with the constructor to initialize state.

  state = { count: 0 }

  // create instance methods for better perf and re-use.

  increment = () => this.setState(({ count }) => ({ count: count + 1 }))
  decrement = () => this.setState(({ count }) => ({ count: count - 1 }))

  // the clean code you've always dreamed of.

  render() {
    return (
      <div>
        <h1>{this.state.count}</h1>

        <button type="button" onClick={this.increment}>+</button>
        <button type="button" onClick={this.decrement}>+</button>
      </div>
    );
  }
}

API

setstate ships with 2 APIs. I know that sounds complicated but it's not.

Object form

This is best used when setting a new value or blowing away a previous value:

this.setState({ name: "Michael" })

Here's what it looks like in response to an input's change event.

// this.state.name gets replaced for every onChange
<input
  type="text"
  value={this.state.name}
  onChange={({ target }) => this.setState({ name: target.value })}
/>

Function form

This is best used when transitioning existing state (like the counter above).

this.setState(previousState => ({ count: previousState.count + 1 }));

This is what it looks like in response to a button press:

<button
  type="button"
  onClick={() =>
    this.setState(previousState => ({ count: previousState.count + 1 }))
  };

Optional callback

setState is asynchronous.

You can use the optional callback to fire code after state is updated.

this.setState(
  { name: "chantastic" },
  () => console.log("the new name is: ", this.state.name)
)

This is handy but not as powerful as using setstate with a React component's lifecycle methods.

Works with React's lifecycle methods

class Counter extends React.Component {
  // look, ma! no callbacks.
  componentDidUpdate(prevProps, prevousState) {
    console.log("current state: ", this.state)
    console.log("previous state: ", previousState)
  }  

  render() { return <div>{this.state.count}</div> }
}

Future

I'm hopeful that this will end up in React proper. When it does, you'll be able to remove the setstate import and everything will work the same.

LICENSE

MIT ® Michael Chan, 2017