Skip to main content

Command Palette

Search for a command to run...

[Part-1] React.js Fundamentals: Building a Strong Foundation

Published
5 min read
[Part-1] React.js Fundamentals: Building a Strong Foundation
A

Anisha Swain | The UI Girl Hello world! Anisha this side👋

💪Making @theuigirl

💻 speaker http://t.ly/9D22 🍀 1:1 https://topmate.io/anishaswain 🎙️ podcast host http://t.ly/_MUml ✏️ blog https://medium.com/the-ui-girl 🧳 Travel story http://t.ly/Xa-5v

https://bento.me/anishaswain Let's connect 🤝

React.js has become a cornerstone in modern web development, providing a powerful and efficient way to build user interfaces. In this comprehensive guide, we'll delve into the fundamentals of React.js, focusing on functional components. Whether you're a beginner or looking to solidify your understanding, this article will take you through the key concepts and practices that form the bedrock of React development.

Understanding Components

At the heart of React lies the concept of components. Components are the building blocks of a React application, encapsulating reusable and independent pieces of the user interface. There are two main types of components in React: functional components and class components.

Functional Components

Functional components are JavaScript functions that take in props (short for properties) as an argument and return React elements. They are simple and concise, making them a preferred choice in modern React development.

Here's a basic example of a functional component:

import React from 'react';

const Greeting = (props) => {
  return <h1>Hello, {props.name}!</h1>;
};

export default Greeting;

In this example, the Greeting component takes a name prop and displays a greeting. Props are a way to pass data from a parent component to a child component.

JSX: JavaScript XML

JSX is a syntax extension for JavaScript recommended by React. It looks similar to XML or HTML but ultimately gets transpiled to JavaScript. JSX makes it easier to write and understand React components.

Let's modify our Greeting component to use JSX:

import React from 'react';

const Greeting = (props) => {
  return <h1>Hello, {props.name}!</h1>;
};

export default Greeting;

JSX allows you to write HTML-like code in your JavaScript files, making React components more readable and expressive.

State and Hooks

State is a fundamental concept in React that represents the data that a component needs to keep track of. In functional components, the useState hook is used to add state to a component.

useState Hook

Consider a counter component:

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default Counter;

Here, count is the state variable, and setCount is the function to update that variable. The useState hook initializes the state to 0. When the "Increment" button is clicked, the setCount function is called to update the state, triggering a re-render of the component.

useEffect Hook

The useEffect hook is used for side effects in functional components. It allows you to perform actions after the component has been rendered to the screen.

import React, { useState, useEffect } from 'react';

const DataFetchingComponent = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    // Fetch data from an API
    fetch('https://api.example.com/data')
      .then((response) => response.json())
      .then((data) => setData(data));
  }, []); // The empty dependency array means this effect runs once after the initial render

  return (
    <div>
      {data ? (
        <p>Data: {data}</p>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};

export default DataFetchingComponent;

In this example, the useEffect hook is fetching data from an API when the component mounts.

Handling Events

React uses a synthetic event system that wraps the native events provided by the browser. Handling events in React is similar to handling events in the DOM but with some syntactic differences.

import React, { useState } from 'react';

const EventHandlingComponent = () => {
  const [buttonText, setButtonText] = useState('Click me');

  const handleClick = () => {
    setButtonText('Button clicked!');
  };

  return (
    <div>
      <button onClick={handleClick}>{buttonText}</button>
    </div>
  );
};

export default EventHandlingComponent;

In this example, clicking the button triggers the handleClick function, updating the state and re-rendering the component.

Conditional Rendering

Conditional rendering allows you to render different components or elements based on certain conditions. This is often achieved using JavaScript conditional operators.

import React, { useState } from 'react';

const ConditionalRenderingComponent = () => {
  const [isLoggedIn, setLoggedIn] = useState(false);

  return (
    <div>
      {isLoggedIn ? (
        <p>Welcome, User!</p>
      ) : (
        <button onClick={() => setLoggedIn(true)}>Log In</button>
      )}
    </div>
  );
};

export default ConditionalRenderingComponent;

Here, the content displayed depends on whether the user is logged in or not.

Props and Prop Drilling

Props are a way to pass data from a parent component to a child component. When a component receives props, it can use the passed data to render dynamically.

import React from 'react';

const ParentComponent = () => {
  const data = 'Hello from the parent!';

  return <ChildComponent message={data} />;
};

const ChildComponent = (props) => {
  return <p>{props.message}</p>;
};

export default ParentComponent;

In this example, the ParentComponent passes a message to the ChildComponent through props.

Prop Drilling

Prop drilling occurs when you need to pass a prop through several layers of components. While this is a common pattern, it can become cumbersome in larger applications.

Consider the following example:

// GrandparentComponent.js
import React from 'react';
import ParentComponent from './ParentComponent';

const GrandparentComponent = () => {
  const data = 'Hello from the grandparent!';

  return <ParentComponent message={data} />;
};

export default GrandparentComponent;
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = (props) => {
  return <ChildComponent message={props.message} />;
};

export default ParentComponent;
// ChildComponent.js
import React from 'react';

const ChildComponent = (props) => {
  return <p>{props.message}</p>;
};

export default ChildComponent;

In this example, the message prop is passed from GrandparentComponent to ParentComponent and finally to ChildComponent. While this works, it may lead to prop drilling when the application grows.

Context API

The Context API is designed to solve the problem of prop drilling. It provides a way to share values like themes, user authentication status, etc., throughout the component tree without passing props manually at every level.

Here's a basic example:

// ThemeContext.js
import React, { createContext, useState } from 'react';

export const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light

Understanding React.js fundamentals lays a robust foundation for building scalable and maintainable applications. We've covered the basics of components, props, state, lifecycle methods, hooks, and routing. As you delve deeper into React development, continue exploring more advanced topics like context, higher-order components, and Redux for state management. React's vibrant ecosystem offers a wealth of resources, enabling you to build powerful and dynamic user interfaces. By mastering these fundamentals, you empower yourself to create efficient, modular, and delightful React applications. Happy coding!

More from this blog

T

The UI Girl

60 posts

Hello world! Anisha this side👋
I am a software developer conference speaker 💻 and a podcast host 🎙️ Loves travelling and digital illustrations 🍀

bento.me/anishaswain Let's connect