Important concepts in React that you should be familiar with

Important concepts in React that you should be familiar with

Table of contents

No heading

No headings in the article.

Components:

A component is a piece of code that returns a JSX element, which can be rendered to the DOM. Components are the building blocks of a React application and can be reused throughout the app to create a modular and maintainable codebase.

Components can be either functional or class-based. A functional component is a plain JavaScript function that takes props as an argument and returns a JSX element. A class-based component is a class that extends the React.Component base class and has a render method that returns a JSX element.

Here's an example of a functional component:

import React from 'react';

function MyComponent(props) {
  return (
    <div>
      <h1>Hello {props.name}!</h1>
    </div>
  );
}

export default MyComponent;

And here's an example of a class-based component:

import React from 'react';

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello {this.props.name}!</h1>
      </div>
    );
  }
}

export default MyComponent;

Props:

Props (short for "properties") are values that are passed to a component from its parent component. They can be used to pass data into a component and customize its behavior.

Props are passed to a component as an object, and the component can access the props using the props parameter. For example:

import React from 'react';

function MyComponent(props) {
  return (
    <div>
      <h1>Hello {props.name}!</h1>
    </div>
  );
}

export default MyComponent;

State:

State is an object that stores data specific to a component. It can be used to track and manage the data that a component needs to function. Unlike props, state can be modified within a component.

When the state of a component changes, React will automatically re-render the component, updating the view to reflect the new state. This allows you to build interactive and dynamic user interfaces.

You can define the initial state of a component inside the constructor method of a class-based component or by using the useState hook in a functional component.

Here is an example of a class-based component that stores a count in its state:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  render() {
    return <div>{this.state.count}</div>;
  }
}

Here is an example of a functional component that stores a count in its state:

import { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  return <div>{count}</div>;
}

Lifecycle methods:

In React, lifecycle methods are methods that are called at different stages of a component's life cycle, such as when it is rendered to the DOM or when it is about to be removed from the DOM. They are a way for a component to perform certain actions at specific points in its life cycle, such as fetching data or updating the DOM.

  1. Lifecycle methods are only available in class-based components, as they are methods of the React.Component base class. Some common lifecycle methods include:

    • constructor(props): This method is called before the component is mounted (added to the DOM). It is a good place to initialize the state and bind event handlers.

    • componentDidMount(): This method is called after the component is mounted (added to the DOM). It is a good place to perform API calls or other side effects that need to happen after the component is rendered.

    • shouldComponentUpdate(nextProps, nextState): This method is called before the component is updated (when the component's props or state change). It should return a boolean value indicating whether the component should be updated or not. If it returns true, the component will be updated; if it returns false, the update will be cancelled.

    • componentDidUpdate(prevProps, prevState): This method is called after the component is updated. It is a good place to perform side effects that need to happen after the component has been updated.

    • componentWillUnmount(): This method is called before the component is removed from the DOM. It is a good place to perform clean-up tasks, such as cancelling network requests or removing event listeners.

Here's an example of a class-based component that uses several lifecycle methods:
import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
  }

  componentDidMount() {
    // Perform API call or other side effect
    fetch('https://my-api.com/data')
      .then(response => response.json())
      .then(data => this.setState({ data }));
  }

  shouldComponentUpdate(nextProps, nextState) {
    // Only update the component if the data has changed
    return this.state.data !== nextState.data;
  }

  componentDidUpdate(prevProps, prevState) {
    // Perform side effect after the component has been updated
    console.log('Component updated');
  }

  componentWillUnmount() {
    // Perform clean-up tasks before the component is removed from the DOM
    console.log('Component unmounting');
  }

  render() {
    return (
      <div>
        {this.state.data ? <h1>{this.state.data.title}</h1> : <h1>Loading...</h1>}
      </div>
    );
  }
}

export default MyComponent;

In a functional component, you cannot use lifecycle methods because they are only available in class-based components. However, you can use the useEffect hook to perform side effects in a functional component.

The useEffect hook is a function that takes a callback function as an argument and is called after the component is rendered. It is a way to perform side effects, such as fetching data or adding event listeners, in a functional component.

Here's an example of how to use the useEffect hook in a functional component:

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

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // Perform API call or other side effect
    fetch('https://my-api.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <div>
      {data ? <h1>{data.title}</h1> : <h1>Loading...</h1>}
    </div>
  );
}

export default MyComponent;

In this example, the useEffect hook is called after the component is rendered, and it performs an API call to fetch data. The data is then stored in the component's state using the setData function. The component renders an h1 element with the data's title if the data is available, or a loading message if it is not.

The useEffect hook takes an optional second argument, which is an array of values that the hook should watch for changes. If any of the values in the array change, the hook will be called again. This is useful if you only want to perform the side effect when certain values change.

For example, you can use the useEffect hook to add an event listener only when the component is rendered for the first time by passing an empty array as the second argument:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Add event listener
    window.addEventListener('click', () => console.log('Clicked'));

    // Remove event listener on unmount
    return () => {
      window.removeEventListener('click', () => console.log('Clicked'));
    };
  },

Hooks:

A hook is a function that allows a functional component to use state and other React features. Hooks were introduced in React 16.8 and are a way to add state and other functionality to functional components, which are components that are written as a JavaScript function and cannot use state or lifecycle methods.

  1. There are several built-in hooks in React, such as:

    • useState: This hook allows a functional component to use state. It returns an array with the current state value and a function to update it.

    • useEffect: This hook allows a functional component to perform side effects, such as making an API call or adding an event listener. It is called after the component is rendered.

    • useContext: This hook allows a functional component to consume a context value. It takes a context object as an argument and returns the current context value for that context.

Here's an example of a functional component that uses the `useState` and `useEffect` hooks:
import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // Update the document title after the count changes
    document.title = `You clicked ${count} times`;
  }, [count]); // Only re-run the effect if count changes

  return (
    <div>
      <h1>You clicked {count} times</h1>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

export default MyComponent;

In this example, the MyComponent component uses the useState hook to add a state value called count, which is initialized to 0. The component also uses the useEffect hook to update the document title every time the count value changes. The component renders an h1 element displaying the current count value and a button that, when clicked, calls the setCount function to update the count value.

Context:

In React, context is a way to pass data through the component tree without having to pass props down manually at every level. This is useful for data that is needed by many components within an application but does not fit the parent-child hierarchy of the component tree.

Here is an example of how you might use context in a React application:

// Create a context for the theme
const ThemeContext = React.createContext('light');

// Create a component that consumes the theme context
function ThemedButton(props) {
  return (
    <ThemeContext.Consumer>
      {theme => (
        <button className={`${theme}-theme`}>{theme}</button>
      )}
    </ThemeContext.Consumer>
  );
}

// Create a component that provides the theme context
class App extends React.Component {
  render() {
    // Provide the theme context value to the tree below
    return (
      <ThemeContext.Provider value="dark">
        <ThemedButton />
      </ThemeContext.Provider>
    );
  }
}

In this example, the App component provides the ThemeContext value to the component tree below it, and the ThemedButton component consumes this context value by using the ThemeContext.Consumer component.

Styling:

  1. There are several ways to style components in React:

    1. Inline styling: You can use the style attribute to apply inline styles to a single component. This is useful for small, one-off styles, but can become cumbersome for larger projects.

       render() {
         return <div style={{ color: 'red', fontSize: '16px' }}>Hello, world!</div>;
       }
      
    2. CSS classes: You can define your styles in a separate CSS file and apply them to components using the className attribute. This is the traditional method of styling web applications, and is a good choice for larger projects with a more complex set of styles.

       render() {
         return <div className="red-text large-font">Hello, world!</div>;
       }
      
    3. CSS-in-JS: There are also several libraries that allow you to define your styles in JavaScript, and apply them directly to your components. This can be a good choice for projects that want to keep all their styling logic in a single place, but it can add additional complexity to your project.

       import styled from 'styled-components';
      
       const RedText = styled.div`
         color: red;
         font-size: 16px;
       `;
      
       render() {
         return <RedText>Hello, world!</RedText>;
       }
      

These are some of the important concepts you should understand in React.

#React #ReactNation #ReaFrica