DEV Community

Cover image for Beginners guide to ReactJS
Ramachandra Petla
Ramachandra Petla

Posted on

Beginners guide to ReactJS

React is client side JavaScript Library that allows us to create Dynamic user interfaces, Single Page Applications (SPA) following the component structure, thereby making the life of developers easy.

This article is for React beginners who is looking to get started with React. In this article you can learn everything you needed to create a web application using ReactJS.

Before moving forward with our little project, lets understand some important concepts of React

  • What are Components
  • Writing Markup with JSX
  • Props and State
  • Handling Events
  • React Hooks

What are Components ?

We can create Components in two ways. Functional components and Class components

Class component

If you want to create a Class component you need to extend the Component class of React, and your class component should have render() method and it is mandatory method. All the JSX syntax is returned inside the render method.

render() methods needs to be pure. i.e. you should not update the component state inside it. Because when JSX tries to render the component it looks for components state and props and renders it again if any changes occurred. If you update component state inside render, JSX will recognize it and render it again and again, which is not acceptable.

If you are wondering about state and props, don’t worry. We are going to learn them below

To create a class component

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Each component has several life cycle methods. These methods can be override with custom code to run at particular times in the process.

Every React Component (Class / Functional) has 3 lifecycle phases: Mounting, Updating, Unmounting.

A component mounts when it renders for the first time

From the second time, Component updates

When the component is removed from the DOM, it is said to be unmounted

Class components has LifeCycle methods that run at each phase.

Mounting Lifecycle methods:

componentWillMount()render(), and componentDidMount()

componentWillMount() will be called first followed by the render() method and finally the componentDidMount() method.

Updating Lifecycle method:

shouldComponentUpdate() it is called before render() is called. Component only renders if shouldComponentUpdate() returns true.

Unmounting LifeCycle method:

componentWillUnmount()

We are not going much deeper into the class components.

With the advent of the Functional components, The use of Class components is minimized. In this article we are going to use Functional Components only.

Functional Component:

With function Welcome() { } you define a JavaScript function with the name Welcome.

This function should have return statement

Functional Components are same are JavaScript Functions, except that their name should start with a capital letter, or they don’t work. function welcome() { } is wrong. function Welcome() { } is right

Sample Functional Component:

function Welcome(props) {
   return (
         <h1>Hello, {props.name}</h1>
     )
}

export default Welcome;
Enter fullscreen mode Exit fullscreen mode

In Functional Components we cannot use LifeCycleMethods, instead we have Hooks which are introduced with React 16.8

We can use functional components same as the Class components.

What is JSX?

JSX is a syntax extension to javascript. Whatever you have seen in the previous section in the return statement is the JSX syntax.

const element = <h1>Hello, world!</h1>;

Consider the statement above. It is neither HTML nor String. It is called JSX. JSX is used to create UI templates by utilizing the full power of JavaScript

In JSX syntax, we can write HTML elements and use React components with In.

<div>
    <h1>Intro Heading</h1>
    <IntroSection />
</div>
Enter fullscreen mode Exit fullscreen mode

This is what a component looks like. We can reuse this component inside other components along with HTML elements and JSX compiler with understands it and converts it into html.

function IntroSection({name, email, address}) {
    return (
        <div>
            <p>Name:{name}</p>
            <p>Email:{email}</p>
            <p>Address:{address}</p>
        </div>
    )
}

export default IntroSection;
Enter fullscreen mode Exit fullscreen mode

When writing JSX in React, there's one caveat: you must return one parent item. Not more than one. For example, this is not possible

These components throws and error

function FuncComp() {
    return (
        <div>Parent 1</div>
        <div>Parent 2</div>
        <div>Parent 3</div>
    )
}
Enter fullscreen mode Exit fullscreen mode

Instead you need to wrap these inside another parent or use special JSX fragment <> </>

it is same as <React.Fragment> </React.Fragment>

//This is going to work

function FuncComp() {
    return (
        <div>
            <div>Parent 1</div>
            <div>Parent 2</div>
            <div>Parent 3</div>
        <div>
    )
}

//This could work as well

function FuncComp() {
    return (
        <>
            <div>Parent 1</div>
            <div>Parent 2</div>
            <div>Parent 3</div>
        </>
    )
}

function FuncComp() {
    return (
        <React.Fragment>
            <div>Parent 1</div>
            <div>Parent 2</div>
            <div>Parent 3</div>
        </React.Fragment>
    )
}
Enter fullscreen mode Exit fullscreen mode

Props and State

Props:

React component uses props to communicate with each other. Every parent component can pass information to their child components in the form of props. You can think of props just like HTML attributes.

function StudentGroup() {
    return (
        <Student />
    )
}
Enter fullscreen mode Exit fullscreen mode

The StudentGroup component has a child component Student

In the above snippet, StudentGroup haven’t passed any props to the Student component

function StudentGroup() {
    return (
        <Student name={studentName} age={studentAge} email={studentEmail}/>
    )
}
Enter fullscreen mode Exit fullscreen mode

The Student component can read the information from the parent component as follows.

function Student(props) {
    return (
        <div>
            <p>Name: {props.name}</p>
            <p>Age: {props.age}</p>
            <p>Email: {props.email}</p>
        </div>
    )
}

// OR (use Object Destructing)

function Student({name, age, email}) {
    return (
        <div>
            <p>Name: {name}</p>
            <p>Age: {age}</p>
            <p>Email: {email}</p>
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

State:

When you create components, It need to preserve some component specific information based on the user interactions. For suppose, you created a counter as a component that increases its value on click of button. The current value of the counter is the information that we are going to store in the state, because we need to constantly update this value on every interaction with the button. Whenever the user clicks on the button, the UI should updated instantly with the new value. This is where the state comes into picture. State is specific to component. Every instance of component has its own state.

The state of component can be managed by its own, or it can be managed by its parent component. If it is managed by parent component, with change in state is affected by all the component instances.

state by component

State managed by Component

state by parent

State managed by Components Parent

For functional component, state is created using useState hook


//State managed by Component
import {useStae} from 'react';

function Counter() {
    const [counter, setCounter] = useState(0);

    const increaseCounter = () => {
        setCounter(counter++);
    }
    return (
        <div>
            <p>Counter: {counter}</p>
            <button onClick={increaseCounter}>Increase Counter</button>
        </div>
    )
}

//State managed by parent
function Counter({increaseCounter}) {
    return (
        <div>
            <p>Counter: {counter}</p>
            <button onClick={increaseCounter}>Increase Counter</button>
        </div>
    )
}

function ParentComp() {
    const [counter, setCounter] = useState(0);

    const increaseCounter = () => {
        setCounter(counter++);
    }

    return <Counter increaseCounter={increaseCounter} />

}
Enter fullscreen mode Exit fullscreen mode

Hooks

React provides a bunch of standard in-built hooks:

  • useState: To manage states. Returns a stateful value and an updater function to update it.
  • useEffect: To manage side-effects like API calls, subscriptions, timers, mutations, and more.
  • useContext: To return the current value for a context.
  • useReducer: A useState alternative to help with complex state management.
  • useCallback: It returns a memorized version of a callback to help a child component not re-render unnecessarily.
  • useMemo: It returns a memoized value that helps in performance optimizations.
  • useRef: It returns a ref object with a .current property. The ref object is mutable. It is mainly used to access a child component imperatively.
  • useLayoutEffect: It fires at the end of all DOM mutations. It's best to use useEffect as much as possible over this one as the useLayoutEffect fires synchronously.
  • useDebugValue: Helps to display a label in React DevTools for custom hooks.

To Create a React application, you need to have npm installed on your machine

Open terminal on mac or CMD on windows and enter the below commands

npx create-react-app react-example
Enter fullscreen mode Exit fullscreen mode

This is going to create a new react project with name ‘react-example’ in the directory where you executed that command

This will the basic directory structure you will get if you create app using create-react-app

Directory Structure

index.js is going to be the starting point of the application

App.js is the First component that is wrapped inside index.js

You can start creating new components and wrap it inside App component

In our next article, we can create a simple website using React. Until then keep messing up with React

Top comments (0)