Search code examples
javascriptreactjscreate-react-app

What is the difference between writing a variable after the render function and writing " this.name of variable " in the constructor function?


What is the difference between writing a variable after the render function like this :

render() {
var headers=[
    { key: 'userId', label: 'User ID' },
    { key: 'id', label: 'ID' },
    { key: 'title', label: 'Title' },
    { key: 'body', label: 'Body' }
];
    return (

and writing " this.name of variable " in the constructor function like this :

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
            users: []
        };

        this.headers = [
            { key: 'userId', label: 'User ID' },
            { key: 'id', label: 'ID' },
            { key: 'title', label: 'Title' },
            { key: 'body', label: 'Body' }
        ];

    }

    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/posts')
        .then(response => {
            return response.json();
        }).then(result => {
            this.setState({
                users:result
            });
        });
    }

    render() {

Other than the fact that when i summon it in the first one i write { headers } and in the second one i write {this.headers}

Note:This is not about var vs this,It's about the structure of the main app class in the create-react-app and its connection with the position in which the previous code is written.


Solution

  • this.someName will become a field on the value of 'this', in your case, the App class. Therefore it is available throughout your App class, e.g. in the render method, or any other instance method, such as componentDidMount, or foo().

    In contrast, if you declare the variable inside the render function, then it's scoped to the render function, i.e. it's not going to be available inside an instance method, e.g. componentDidMount.

    If you define the variable in the render method, then it's just that, a variable within a method, thus it's going to get instantiated on every call to the render function, that could be expensive, if there's no good reason for that additional overhead, then declaring the variable on this would be a sensible option.

    Only other thing that comes to mind to mention is that changing the value of a class field will not queue a render, whereas if a given value is defined in the state object of a React component class, then this will trigger a new render.

    PS - It's not 100% clear what you're asking.