Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Which is better to use three definitions of variables in React ES6? Why? #11839

Closed
xiubug opened this issue Dec 13, 2017 · 3 comments
Closed

Comments

@xiubug
Copy link

xiubug commented Dec 13, 2017

// One
const arr = [7,8,9]; 
class WatchStore extends Component {
  constructor(props) {
     super(props);
   }
   ......
}

// Two
class WatchStore extends Component {
  constructor(props) {
     super(props);
     this.state = {
       arr: [7,8,9],
     }
   }
   ......
}

// Three
class WatchStore extends Component {
  constructor(props) {
     super(props);
   }
   componentDidMount() {
     this.arr = [7,8,9]; 
   }
   ......
}

which is the best way to use the three defined methods?
The arr does not need to be rendered, just make a temporary cache comparison new data use!

Thanks!

@xiubug xiubug changed the title Which is better to use three definitions of variables in react ES6? Why? Which is better to use three definitions of variables in React ES6? Why? Dec 13, 2017
@swyxio
Copy link
Contributor

swyxio commented Dec 13, 2017

hi, all can do what you need, it just depends on what you want to do in the end. in particular your method Two stores the array in state so setting that state will trigger a rerender, whereas the other two methods you gave will involve mutating the array without rerendering the component.

This is more of a question of opinion/code style and so is not a suitable issue to raise in this github repo. please have a look at https://reactjs.org/community/support.html for more appropriate venues of community support. thanks!

@mrchief
Copy link

mrchief commented Dec 13, 2017

Agree with @sw-yx. My 2 cents:

Option 1: Doesn't allow mutation. Go with this if you want to enforce this.

Option 2: Allows mutation, triggers re-rendering on mutation.

Option 3: Allows mutation, no re-rendering on mutation.

For your specific use case, Option 1 is the best choice.

@clemmy
Copy link
Contributor

clemmy commented Dec 14, 2017

As @sw-yx and @mrchief pointed out, option 1 is the best choice for your use case, and issues not related to the React library itself should go into the appropriate channels.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants