loading...
Cover image for My Thoughts After Learning React For 3 Months

My Thoughts After Learning React For 3 Months

fahadimran profile image Fahad Imran ・9 min read

React is one of the most popular Front-End JavaScript frameworks. Developed by Facebook in 2013, it is actively maintained as an open source project, and has made building complex user interfaces easier. That's why it is one of the most loved frameworks even in 2020.

A Little Backstory...

I, like many Front-End Developers started learning React after I had become comfortable writing HTML, CSS and JavaScript. Because of their extensive usage in the market, I knew I had to learn a JavaScript framework as well. I thought long and hard before making my decision between React, Vue and Angular. I finally settled on React because I liked the flexibility it provided and I knew that, because of its popularity, I would have no trouble finding help online in case I got stuck.

Thus, I have been using React for the past 3 months, in various projects, to learn what's it all about. Naturally, as a new developer starting out with React, I gained much needed insights about the state of React ecosystem. I am sharing some of my thoughts for new developers who are learning React or are considering switching to it.

OK, enough blabbering. Lets jump into it!

1. Flexibility...

The first thing I noticed when I started working with React is, how flexible it was, and how much freedom it provided to the developers. At the core React is just a basic library, but functionality can be easily added on top of it by different libraries and packages.

The best thing about React is that there are no restrictions or strict guidelines in terms of coding style that you have to follow. You can choose to create your components however you want, whether it be class or function components, you can adopt styled components or choose to split you application into dumb and smart components to ensure separation of concerns. Everything is up to the developer. Sure, there are some recommended best practices that you can follow, but no one is going to shove a certain application structure, down your throat if you don't like it.

While this flexibility is definitely welcome to some developers, others might argue that it makes it difficult for newbies to get started. I, also somewhat agree with this point of view. As a new React developer myself, I was initially quite confused at what the correct way was to create Apps with React. Since, every tutorial and article I looked at was telling me a different way of doing things. It was only later that I realized that there is no best way to write React. As long as you become comfortable with the core concepts like Components, State, props, JSX etc. you can pretty much adopt the style what works best for you. So, that's what I have been doing for some time now, and it is working fine so far.

2. What's JSX...

React uses what we call JSX, which is a mixture of JavaScript and HTML. Though, at first I despised the idea of JSX, since, we have been taught from the beginning that it's a bad practice to mix in JavaScript with your markup. Here's what it looks like:

<form
  onSubmit={editInput === '' ? getTodoText : getEdittedText}
  className="mt-4"
>
  <div className="input-group">
    <input
      type="text"
      placeholder="Add a todo item..."
      className="form-control"
      onChange={editInput === '' ? getInputValue : changeEditValue}
      value={editInput === '' ? input : editInput}
    />
    <div className="input-group-append">
      <button
        type="submit"
        className={getClassName()}
        disabled={input === '' && editInput === '' ? true : false}
      >
        {getButtonName()}
      </button>
    </div>
  </div>
</form>

But after some practice, I realized the power it brings to the table. By having your markup and JavaScript together, you can effectively control the entire functioning of the App from a single source. Here's the reasoning that React provides:

"Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both."

In simpler terms, instead of separating the entire app logic from markup, React separates out the app into different components which contain both their respective logic and markup. This ensures that even though individual components contain both the HTML and JavaScript, yet the entire App is well separated into different components which handle separate functionalities.

While writing JSX might seem daunting at first, trust me, you'll get used to it in no time and will enjoy it too.

3. Know Your JavaScript...

When you start learning React, one thing you will quickly understand is the importance of having strong grasp over JavaScript Fundamentals.

While React might use JSX, but at its core its just a mash up of HTML and Vanilla JavaScript. Without sound knowledge of JavaScript, you'll have a hard time understanding and using React. Because, you will be learning both React and JavaScript at the same time and you won't be able to master either of them.

In order to excel at React, a good understanding of JavaScript is must. Especially the new ES6 syntax. It is essential that you understand concepts like Arrow Functions, Object Destructing, Higher Order Array methods, JavaScript Objects, Arrays etc. As more often than not you will have to use them in your React Apps.

I cannot tell how many times I had to use higher order array methods like map() and filter() or how many times I created functions using the Arrow Function syntax.

return (
  <React.Fragment>
    <ul className="list-group mt-4">
      {itemList.map((item) => {
        return <Item name={item} key={item} />;
      })}
    </ul>
  </React.Fragment>
);
export const About = ({ history }) => {
  return (
    <div>
      <p className="m-3">You are on the About Page 😎</p>
      <button
        className="btn btn-dark mx-3 my-2"
        onClick={() => {
          history.push("/");
        }}
      >
        Back To Home
      </button>
    </div>
  );
};

Thus, my advice to new devs, starting out with React is, to first master the basics of JavaScript before moving on to React. It will not only make your life easier, but you will also understand the core concepts of React better, instead of fiddling around with JavaScript concepts.

4. Class Vs Function Components...

When I was starting out with React, I got confused between choosing Class components and Function Components for my projects. The major difference between them apart from their syntax, was that if you were using class components, then you could use State in your component, something which was not possible in function components at that time. Furthermore, with class components, you had access to life cycle methods like componentDidMount(), componentDidUpdate() etc.

Here's a quick comparison between a very simple class and function component:

A typical Class Component

import React from "react";

export class YourComponentName extends React.Component {
  state = {};

  render() {
    return <div>Hi, I am a class component.</div>;
  }
}

A typical Function Component

import React from "react";

export const YourComponentName = () => {
  return <div>Hi, I am a functional component.</div>;
};

So, the easy recommendation was that, if you wanted to make your component stateful, you would use class components, if not then you would use function components. Easy, right? Well... not necessarily.

Just as this concept was about to make sense, I discovered React Hooks. I will go more into detail about what Hooks are, and why they are awesome in a later section, but the long and short is that, React Hooks allow us to add state and life cycle methods to function components.

So, your function components now look like this:

import React, { useState } from "react";

export const YourComponentName = () => {
  const state = useState({});

  return <div>Hi, I am a stateful function component.</div>;
};

At first, I was quite bummed, to say the least, as I had become accustomed to using class components. But, after using function components with hooks for some time, I was hooked 😉. Now, I have switched to exclusively using function components in all my applications as they are short and concise and anytime I need state in my components, I can easily add it through hooks.

5. The Power of React Hooks...

Now let's talk about React Hooks. Hooks were introduced in React 16.8. Hooks allow you to use state and life cycle methods in function components. Thus, they allow you to write function components that are essentially the same as class components, since they can include state and other React features.

According to the official documentation:

"Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class."

There are different types of hooks and each is as useful as the next. I won't go into details about each and every hook, but will show a brief example on how I have used them. If you want more information about Hooks consider looking up the official documentation.

The most common hook is the useState hook which allows you to add state to any function component. It is extremely easy to use and comes in handy more often than not.

import React, { useState } from "react";

export const MyComponent = () => {
  const msg = useState("Hello World!");

  return <div>The message is {msg}</div>;
};

Another hook which I have used in my projects is the useEffect hook which is similar to the life cycle methods componentDidMount and componentDidUpdate. So, if you want to make API calls or use any other side effects, useEffect is the hook to use.

useEffect(() => {
  fetch("/api/stationeryItems")
    .then((res) => res.json())
    .then((data) => {
      setData(data);
    })
    .catch((err) => {
      console.log(err.message);
    });
}, []);

Finally, if you want to add Redux like functionality in your application, there are 2 hooks which mimic the core state management features. These are useContext and useReducer hooks. These along with the new Context API allow for complete state management without using Redux.

// useReducer() hook
const [state, dispatch] = useReducer(LibraryReducer, initialState);
export const Book = () => {
  // useContext() hook
  const context = useContext(LibraryContext);
  return (
    <React.Fragment>
      <p>I am inside the Book Component 🥳</p>

      {/* Book Information */}
      <p>Book Name: {context.state.name} </p>
      <p>Quantity: {context.state.quantity}</p>
      <p>Book Shelf: {context.state.shelf}</p>
      <button onClick={context.incrementQuantity}>
        Increment Quantity
      </button>
    </React.Fragment>
  );
};

I will talk more about state management in the next section, but suffice it to say that hooks have really changed the way I write React code. They have allowed me to add any functionality, I think of in my function components. React Hooks have drastically reduced the amount of code I write, while increasing my productivity along the way.

6. State Management...

Naturally, as with any JavaScript Framework, whether it be Angular, React or Vue, state management is an important concern. In Single Page Applications, it is essential to keep the state consistent between different components and ensure that it gets updated correctly. React is no different.

Therefore, an important concept all React devs should understand is how to effectively manage state in their applications. When I was starting out with React, I was stressed about state management since I knew that React did not include a built in state management solution at that time. Therefore, most of the online articles and tutorials recommended using Redux. And I had heard that Redux was difficult to learn, it required a lot of boiler plate code and made your application size larger and so on... So state management was one of my biggest concerns as a new React developer.

But now, after working with React for some time, I realized that state management is not actually as difficult as it seems. From what I have gathered there are essentially 3 ways to manage state in your React apps. I will not go into details here, since I plan to write a separate comprehensive blog about state management with pros, cons and code examples. Here, I will briefly touch on the different methods you can use.

The first method is to lift the state to the parent component and pass it to child components through props. This is by far the easiest method to implement but it is only suitable for small applications and does not scale well.

The second and most common method is to use a third-party library for state management. The most common library used with React is Redux. It is one of the most popular state management solutions and has become an industry standard. Though, it scales well to larger applications but it involves a lot of boiler plate code and adds to the package size.

The third and newest method of State Management in React is using the Context API. This is by far my favorite method of state management, as it is built into React and therefore, it does not require any third-party library to be installed.

Here's what the official documentation says about Context API:

"Context provides a way to pass data through the component tree without having to pass props down manually at every level."

Thus, Context allows you to keep the state separate from the Components and access it in whichever component you want without having to pass it as props.

Context API by itself, is a pretty powerful tool. But Hooks like useReducer and useContext take it to a whole new level and make it a viable alternative to even Redux. Combining Context API with Hooks provides you an effective and elegant solution to state management which is built directly into React.

Thus, I have been playing around with Context API for some time now, and in my opinion, it is a worth while state management solution that all new React devs should try before jumping into Redux.

Closing Thoughts...

In the end, I would say that using React has been a great experience for me. I am still a beginner and I am learning a lot of new things everyday. But I wanted to share some of the important points and tips that I have discovered since I started using React. Some of these things drove me absolutely crazy, while I was starting out, since I found very conflicting advice on the internet. Therefore, my goal was to share a one stop guide for programmers who are starting to learn React, like I was, enlisting what I believe, are the most important things to keep in mind as you progress 😊.

Posted on by:

fahadimran profile

Fahad Imran

@fahadimran

Aspiring software engineer | Passionate about web development | NodeJS and React | Tea drinker

Discussion

markdown guide
 

Try Mobx. For me, hooks haven't changed my mind. Sticking with Mobx for state management. Simple, natural, and powerful. As old and stabile as Redux. I dont have a clue why Redux became industry standard and not Mobx.

 

You don't need Mobx and your don't need Redux for 90% of Apps you build. Look into useReducer hook. Also hooks are the new standard and writing class components only because it is the first thing you learned is not smart.

 

Ivan, classes are actually the last thing I learned :D its not about classes, or "standards". Its where you feel comfortable, what fits your way of work. There are no "standards" in Javascript, React especially. If i wanted to go that way I'd probably go with Angular. All those mentioned tools are going to get the job done. Tried hooks, tried Redux... Not found either worthy my time do dig deeper and force myself to use it. I have limited time and long learning list. Mobx stays :) As I said in my original post ... Im not a mainstream guy. If "everybody" uses it, has no meaning to me.

I'd argue against classes because they have always been a concession to developers coming to JavaScript from class-based languages, and lull you into a false sense of security in thinking you can bend JavaScript to behave like those other languages.

Furthermore, at a certain level of complexity you're probably duplicating a ton of code in your un-reusable class methods (one of the primary motivators for React hooks).

An even simpler case can be made against classes just by making the same component twice, in a functional and class version, and comparing the transpiled results. The output will be much cleaner/smaller for the functional version, and that disparity only grows as the component grows in complexity.

Yes it's true that nobody forces you to be mainstream, same would also be true for a AngularJS developer not to care about new Angular, but where I see the most you loose (if you care) are libraries around react, all UI libraries and for example graphql apollo and even Mobx and Redux came out with hook version, also many libs started to focus hooks only, so I see here a problem because class compoents where before big and had duplicated code but if you are forced to do a lot of custom stuff the components will get even bigger. Mabe just use it for a few days again, maybe you see why it's here.

Ivan, i was referring to useReducer, useContext hooks since discussion was about state management. I do use React hooks, completely removed classes and converted to functional components. But I have not used React "state" management before nor now when mentioned apis/hooks were introduced.

I do keep Mobx stores in classes. They feel appropriate there and I like classes whrn managing state. I just don't like classes in UI layer of the app. Functional React components there are what I prefer.

I might misunderstood you, izvini :D If mobx is your thing keep using it why not.

@psiho just keep in mind that you're leaving something on the table when it comes to bundle size reductions. Classes do not transpile cleanly.

Haven't really thought about that. My bundle size was always acceptable. I did play with optimizing it much more lately, but mostly I used chunks, dynamic loading and removing unnecessary libraries (react-router is my favourite victim there for less complex apps). My Mobx stores chunks were allways very low on the list, tiny compared to other gains, so I havent checked (nor known) this. Can you shed some light on this? How large bundle size gains I can expect by avoiding Classes?

I can't give a number, but doing the 1-1 function component vs class component transpiling comparison was an eye-opener.

FWIW I've avoided using ES6 classes outside of React components (and thankfully now with them too) for a long time in any codebase I wasn't inheriting.

As for React Router, look into v6 (still in beta, but already very stable). It's WAY lighter than v5.

Yeah agree I already use the beta in production.

 

Thanks for the advice ❤ I haven't used Mobx yet, but I will definitely try it. I picked up Redux because when I started out with React, everyone was saying how it's necessary to learn Redux for any large scale project. I never got around to trying out any other state management solution. It's only recently that I learned about the Context API and how many devs are switching to it instead of Redux. I am really not a fan of Redux and I try to avoid it as much as possible because I find it difficult and cumbersome to use. Anyways, thanks for recommending Mobx. I will look into it. It might be just what I need 😊

 

While I wouldn't recommend it for anything even close to production yet, keep a close eye on Recoil. It's already getting a lot of things right in state management.

Regardless of your global state solution, context and hooks are great for managing shared state among small localized component clusters ("molecules" if you will, speaking in atomic design lingo), and can even be a great global solution if you plan for multiple contexts wisely.

Constate is a library based on that multi-context model, and it's one of only two state management libraries at the moment (IIRC) that works flawlessly with React's new Concurrent Mode.

 

Was exactly in the same boat years ago. But I tend to be reserved about mainstream solution, always trying to try something else. That's how I started with Mobx and happy ever since. Now you also have the option of a Mobx tree if your style/project need that.

While I agree that you shouldn't just look to the mainstream solution, you shouldn't discount it just because it's mainstream (you are, after all, using the most popular UI library on the planet).

I personally jumped the Redux ship because of its boilerplate (which isn't as bad as it used to be, but still too much) as since as hooks and context started delivering on the promise of more than just local state management within React (and with atoms and selectors, Recoil has even more promise), but Mobx's boilerplate has always bothered me too.

But Redux emerged as the top choice because, in spite of this, it accomplished some pretty amazing things in a very concise (and extendable) codebase. I don't have to love all of of its decisions or even think it's the right choice for me to appreciate its enormous achievement.

 

Context API instead od Redux? That’s misunderstanding. I thought Redux targets far apart components. It’s meant for huge projects(like Facebook). Context API is made for close relative components

I agree Redux has its use cases. Of course for large projects(on the scale of Facebook etc), Redux is more suitable since its advantages outweigh the initial setup code. But for small projects(which someone like me would work on), Context API provides a nice alternative instead of directly jumping into React.

For me, the Context API feels outdated. The need for placing the Provider is confusing and leads to unintentional re-renders. I even saw a post where someone suggests using Context API as a global store 😁. There are plenty of solutions available. Take a look at Hookstate, Effector, MobX

leads to unintentional re-renders

This is my biggest gripe with Context API. It has its uses in very small contexts, but any large state, forget about it.

Even with Redux, I've argued for a long time that you should use more than a single state store in a larger project. Dumping all your state into a single global store is just asking for bad things to happen, and often it's just lazy.

As there is not (yet) an official useContextSelector hook, it becomes more critical to break your state down into more localized context providers; however, this really isn't that challenging even in larger codebases. It actually can be a really great way to organize your code (and you are documenting it, right?).

I couldn't imagine dumping all your state into a global store, but I suppose some do may do it.

@fkrasnowski and @jamesthomson think of Redux vs. context for "global" state like this: Compare SQL and NoSQL (or in a similar sense, block storage vs. object storage).

In the former, the typical thinking is that you dump it all in one store (with SQL and block storage, as the answer to expensive storage), then obsess over optimizing (or defragmenting), indexing, or in Redux grabbing from all over with selectors, etc.

In the latter (with NoSQL and object storage emerging as storage became cheaper), you typically plan things out in much shallower hierarchies. It's nothing to create a thousand different NoSQL databases, and it's trivial to create multiple contexts much lower down the component tree rather than reaching up to a top level store.

Like NoSQL (or graph, or other DB) solutions are beginning to emerge with more SQL-like index/join/etc. capabilities, we're beginning to see selector capabilities arise for context solutions. In both cases, it's a "best of both worlds" solution. Daishi Kato's work is pushing this forward by e.g. already implementing the proposed useContextSelector hook, as is Facebook's own experimental Recoil library.

 

Your post mirrors my experience with learning React very well. One point I'd like to reiterate is know your JavaScript. I've tried learning React several times and I've found it so hard because my JavaScript skills weren't very good.
Great post!

 

I jumped in to learning React a lot sooner than I probably should have. I had an insubstantial grasp on HTML, CSS, and JavaScript, but knew enough to make small static pages. Fast forward to almost two years later. I have worked with a lot of C# and even did a small 6 month stint as a front end developer where I used Angular. Very recently (last week), I decided I would jump back in to React because I had enjoyed it when I first used it. I have to say, I am definitely able to pick up on things a lot quicker now versus two years ago.

 

It happened with me as well. I was looking into JavaScript frameworks way before having a sound knowledge of JavaScript Fundamentals. Thankfully, I was able to realize my mistake. I am a big fan of Brad Traversy and watch quite a lot of his videos. He stressed that it is very important to learn basics of JavaScript, especially the new ES6 syntax, before jumping into React. I followed his advice and my React learning experience improved tremendously. Now that I have spent a bit more time with React, I can definitely say that the time you invest in learning JavaScript will pay off and learning React will become a whole lot easier.
Thanks for sharing your experience ❤

 

THIS. People are already worried about React becoming the new jQuery (lots of great jQuery/React devs, who can't write JS to save their lives). Don't contribute to that.

While React is in some ways much closer to vanilla JS than jQuery was (even if jQuery informed a lot of the things we now take for granted in modern JS, and React encourages a lot of good JS thinking), in others it's abstracted much further away from it.

You need to understand why something works or doesn't work according to the React way of doing things, but it's also important to know the underlying JS that makes it work or not.

 

With arrow function, you can write stateless component shorter:

export const YourComponentName = () => <div>Hi, I am a functional component.</div>;
 

My bad. I totally forgot that in arrow functions you can omit curly braces if there is a single expression. I have developed a habit of putting curly braces (coming from Java and ordinary function syntax) 😅 Thanks for the heads up 👍

 

Really accurate about hand guiding tutorials. Thus, my favourite way to learn something is documentation 😌

 

This was an extremely well written article. I wish I had it a few months ago. Kudos!

 

Excellent guide for beginners.

 

I tried learning react but I didn't enjoy it because there was barely any separation between js and HTML.