GithubHelp home page GithubHelp logo

rickhanlonii / setstate Goto Github PK

View Code? Open in Web Editor NEW

This project forked from learnreact/setstate

0.0 2.0 0.0 9 KB

Set local state in a React.Component

Home Page: https://www.npmjs.com/package/setstate

License: MIT License

JavaScript 100.00%

setstate's Introduction

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, previousState) {
    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

setstate's People

Contributors

chantastic avatar siddharthkp avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.