Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 15, 2020 07:55 am GMT

My Thoughts After Learning React for 3 Months

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 the 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. Let's 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 the 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 functional components, you can adopt styled-components or choose to split your 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 that 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 that 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, it's 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 Functional Components...

When I was starting out with React, I got confused between choosing Class components and Functional 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 functional 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 functional 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 Functional 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 functional 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 functional components.

So, your functional components now look like this:

import React, { useState } from "react";export const YourComponentName = () => {  const state = useState({});  return <div>Hi, I am a stateful functional component.</div>;};

At first, I was quite bummed, to say the least, as I had become accustomed to using class components. But, after using functional components with hooks for some time, I was hooked . Now, I have switched to exclusively using functional 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 functional components. Thus, they allow you to write functional 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 of 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 functional 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 that 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() hookconst [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 functional 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 boilerplate 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 yet, it involves a lot of boilerplate 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 worthwhile 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 every day. 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 .


Original Link: https://dev.to/fahadimran/my-thoughts-after-learning-react-for-3-months-1bib

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To