News for hackers. Stuff that matters.
Re:JavaScript fundamentals before learning React by rwieruch on Thursday July 19, 2018 @06:17PM (#17570831)
Hey, author here :) I am curious about your experiences using/learning React. Are there any other JavaScript topics which are important when starting out with React? Would be great hearing your opinion!
Re:JavaScript fundamentals before learning React by hoorayimhelping on Thursday July 19, 2018 @08:59PM (#17571674)
This is great! Great write up and good idea on what to actually write about.

One suggestion I'd make is to use ES6 template literals over concatenation, since you're using other ES6 constructs anyway.

    getName() {
      return `${this.firstname} ${this.lastname}`;
    }
Cleaner and less error prone. On our team we had a convention to only use backticks when we intended to combine strings, so that if you ever saw a backtick, you knew a string was being built, likely for output.
Re:JavaScript fundamentals before learning React by rwieruch on Friday July 20, 2018 @01:50AM (#17572794)
Included it :)
Re:JavaScript fundamentals before learning React by sorahn on Thursday July 19, 2018 @09:41PM (#17571822)
It’s worth noting that using the fat arrow syntax for class functions make them exponentially harder to unit test because they do not exist on the Prototype of the component, but are instead only initialized when the class is initialized.

If you are trying to unit test a function that calls another function in the same class you cannot mock the second one it if it is a fat arrow.

Re:JavaScript fundamentals before learning React by dvlsg on Thursday July 19, 2018 @10:13PM (#17571937)
I feel like testing things by replacing pieces of a prototype would be fairly fragile anyways. Is there a reason you couldn't use some form of composition to mock / abstract your dependencies instead?
Re:JavaScript fundamentals before learning React by sorahn on Thursday July 19, 2018 @10:24PM (#17571977)
Given this super contrived example: https://gist.github.com/sorahn/2b287c2a97a12e318585e84d9a9e8...

If 'baz' was a fat arrow function, you would never be able to test bar in isolation.

for example: Jest is set up so it's super easy to say `jest.spy(Foo.prototype, 'baz').mockReturnValue('whatever')`and test that bar is doing the right thing.

Re:JavaScript fundamentals before learning React by Touche on Thursday July 19, 2018 @10:35PM (#17572026)
Mocking should only be used for extreme circumstances. This class is very easy to test without mocking. `bar` takes no arguments and has no external dependencies and therefore should always return the same result.
Re:JavaScript fundamentals before learning React by sorahn on Thursday July 19, 2018 @10:42PM (#17572054)
OK, you caught me, give bar an argument. (I'll edit the gist)

Why should mocking only be used in 'extreme circumstances'? I want to test what bar does, and I don't care what baz does, and if someone breaks baz, my unit tests for bar shouldn't fail, because it is doing its job.

I would mock it if it was calling some function in another module, so what's the difference if it's calling another function in the class?

Re:JavaScript fundamentals before learning React by yorwba on Friday July 20, 2018 @12:00AM (#17572347)
Mocking a component means that you now have two places where that component's behavior is specified and they can diverge. To prevent that, you'll need an integration test where the components interact directly. Just not using a mock is enough to get such an integration test.

Then the value of the original, mocked unit test is questionable. It only provides additional information in the event that the mock differs from the actual component. If that's unintentional, then either the component is wrong (which should be caught by the tests for that component) or the mock is wrong. In either case, the mocked test provides little or negative value.

Then the remaining case, where mocking is actually useful, is when the mock intentionally shows different behavior. Mocking a slow computation to return the result instantly. Deliberately failing, to test error-handling code. Simulating unlikely events in general. Those are good uses of mocking.

TL;DR: Write more integration tests instead of unit tests with mocking.

Re:JavaScript fundamentals before learning React by sorahn on Friday July 20, 2018 @12:23AM (#17572439)
> TL;DR: Write more integration tests instead of unit tests with mocking.

Interesting. I will investigate what that looks like at work tomorrow. Thanks!

Re:JavaScript fundamentals before learning React by jholman on Friday July 20, 2018 @07:49AM (#17574205)
I also think it's worth noting that fat arrow class methods is not a feature of JavaScript/ECMAScript, but rather a feature of Babel. It might make it into a future standard, but so might decorators (including autobinding decorators) or double-colon syntax for binding. None of these is currently legal vanilla JS.
Re:JavaScript fundamentals before learning React by k__ on Thursday July 19, 2018 @07:39PM (#17571313)
Nice writeup!

I wrote a tutorial that would be the next step to yours, called React From Zero[0] I try to teach React here with the basic JavaScript knowledge most people already have.

[0] https://github.com/kay-is/react-from-zero

Re:JavaScript fundamentals before learning React by scns on Friday July 20, 2018 @03:09AM (#17573050)
I can recommend this, having only read the first two, very enlightening. Thank you for your work.
Re:JavaScript fundamentals before learning React by michael_michael on Thursday July 19, 2018 @11:46PM (#17572281)
I am learning React and ES6 currently. I dove into React before really understanding ES6, and your article is really helping to illuminate some of the dark corners of JS. Thank you.

One section I was hoping would get more treatment in your article (like the same treatment you gave classes, which was great) was imports/exports. Named vs. default exports are kind of baffling for a newcomer, and the usage of the named import with curly bracket syntax seems completely arbitrary.

I am sure there are many, many good explanations of named vs. default imports/exports out there on the Internet, but this is one that leaped out at me. I was a little disappointed that the section on imports/exports was so comparatively short. It mostly discussed the usage of imports/exports in CRA.

Still, awesome article. Thanks again.

Re:JavaScript fundamentals before learning React by rwieruch on Friday July 20, 2018 @02:19AM (#17572902)
Extended the section about imports and exports. Thanks for your feedback!
Re:JavaScript fundamentals before learning React by cygned on Thursday July 19, 2018 @11:19PM (#17572179)
I think, the most important aspect I tell my developers is to not define functions inline during render. So, do not do this:

    <button onClick={ () => this.smth() }></button>
This creates a new function every time the rendering happens and mutates the prop onClick on every render. Once you have a component with a lot of elements (e.g. inputs) and child components that check for changes props to determine whether to render, this will get you in performance trouble.

We do not use class arrow functions but instead have helpers to bind specific functions to the component's context or generate setter functions.

Re:JavaScript fundamentals before learning React by wongma on Friday July 20, 2018 @12:07AM (#17572381)
I usually do this when I need to pass arguements in:

  <button onClick={ (arg) => this.smth(arg) }></button>
How can I do this without defining a function?
Re:JavaScript fundamentals before learning React by cygned on Friday July 20, 2018 @02:34AM (#17572950)
For simple use cases, we also use this pattern, however, usually moved to separate functions for readability, real example:

    createOpener(folder) {
        return () => this.props.dispatch(Actions.listFiles(folder, this.props.member));
    }
As said, for more complex layouts we need to reduce moving parts. For example, we have input masks that can easily consist of 200 input fields alone plus all kinds of other components. What we do in that case is usually pre-binding functions with arguments. Roughly like this:

    // Target function
    onItemClicked(item) {
        // ...
    }
    
    preBind() {
        const { data } = this.props;

        // Bind with primary key
        data.forEach(item => {
            this[`__boundFn_data_${item.get('primaryKey')}`] = this.onItemClicked.bind(this, item);
        })
    }

    render() {
        const { data } = this.props;

        return <Fragment>
            {
                data.map(item => {
                    const pk = item.get('primaryKey');

                    return <div key={pk} onClick={this[`__boundFn_data_${pk}`]}>{ item.get('label') }</div>
                })
            }
        </Fragment>
    }
This approach involves a lot more complexity concerning removing bound functions and caching. And things like function name generation is stored in separate functions etc. It's not trivial but you get some performance out of it.

By doing this, though, we can rely on props checks for components to determined the necessity of rendering which allows us to use React's PureComponent in 90% of our components.

Re:JavaScript fundamentals before learning React by minitech on Friday July 20, 2018 @02:32AM (#17572941)
> How can I do this without defining a function?

You do define a function, but only once. Constructor:

  this.smth = this.smth.bind(this);
JSX:

  <button onClick={this.smth}></button>
Kind of awkward, but the standard practice last I checked. Arrow methods (terminology?) are also something you can add to the language that does the equivalent of .bind() replacements.
Re:JavaScript fundamentals before learning React by tills13 on Friday July 20, 2018 @12:23AM (#17572438)
isn't that functionally equivalent to `onClick={ this.smth }`?
Re:JavaScript fundamentals before learning React by barskern on Friday July 20, 2018 @01:30AM (#17572705)
No it is not equal because the former autobinds `this` into the body of the arrow function, however the latter is "just" a function pointer hence will not be called with the correct `this` value. One way to get around this is using `this.smth.bind(this)`, which binds the correct `this` for the later execution.
Re:JavaScript fundamentals before learning React by wongma on Friday July 20, 2018 @01:51AM (#17572797)
no, because you're not passing the arg in now right?
Re:JavaScript fundamentals before learning React by williamdclt on Friday July 20, 2018 @06:33AM (#17573843)
Of course you are. The `smth` method will receive whatever arguments the caller gives.

This totally works but only if `smth` has been declared as an arrow function (so that is captures the class `this` context).

Re:JavaScript fundamentals before learning React by kansface on Thursday July 19, 2018 @06:57PM (#17571076)
Formatting strings (template literals [1]) comes up frequently for constructing ids/refs/various other props.

1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

Re:JavaScript fundamentals before learning React by rwieruch on Friday July 20, 2018 @01:51AM (#17572796)
Included :)
Re:JavaScript fundamentals before learning React by vga805 on Thursday July 19, 2018 @07:35PM (#17571297)
hey there, nice write-up

two minor things that you might include are

1: rest in the context of function args

2: short circuiting: e.g. `isLoading && <Loading />`

Re:JavaScript fundamentals before learning React by rwieruch on Friday July 20, 2018 @01:54AM (#17572808)
Included. Thanks :)
Re:JavaScript fundamentals before learning React by rsyring on Thursday July 19, 2018 @06:38PM (#17570954)
May want to point out you are the author of the article. :)
Re:JavaScript fundamentals before learning React by rwieruch on Thursday July 19, 2018 @06:40PM (#17570973)
Done :)