Who loves creating apps.

Tag: react (Page 2 of 2)

React : Props, State, and Lifecycle Methods

Props and State in Class Components

Class components in React are defined using ES6 classes. Two central concepts in these components are props and state.

  • Props are read-only attributes used to pass data from a parent component to a child component. They make components reusable by giving them the ability to receive data from their parent component.
  • State is a component’s private data. It allows components to create and manage their own data. State changes can be asynchronous, and updating the state re-renders the component.
class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.state = { age: 25 };
  }

  render() {
    return (
      <div>
        <h1>{this.props.name}</h1>
        <p>Age : {this.state.age}</p>
      </div>
    );
  }
}

But…

Props and State in Functional Components with Hooks

With the introduction of Hooks in React 16.8, functional components gained the ability to use state and other React features without writing a class.

  • useState() is a Hook that lets you add React state to functional components.
import React, { useState } from 'react';

function UserProfile({ name }) {
  const [age, setAge] = useState(25);

  return (
    <div>
      <h1>{name}</h1>
      <p>Age: {age}</p>
    </div>
  );
}

Lifecycle Methods in Class Components

Lifecycle methods in class components allow you to run code at specific points in a component’s lifecycle, such as when it mounts, updates, or unmounts.

  • componentDidMount(): Invoked immediately after a component is mounted. Perfect for initialization operations such as fetching data.
  • componentDidUpdate(): Invoked immediately after updating occurs. Use it for DOM updates based on state or props changes.
  • componentWillUnmount(): Invoked immediately before a component is unmounted and destroyed. Useful for cleanup activities like invalidating timers.
class UserProfile extends React.Component {
  componentDidMount() {
    console.log('Component did mount');
  }

  componentDidUpdate() {
    console.log('Component did update');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  render() {
    return <div>User Profile</div>;
  }
}

Lifecycle Methods in Functional Components with useEffect()

For functional components, the useEffect() Hook serves the purpose of lifecycle methods, enabling side effects in these components.

  • useEffect(): Accepts a function that contains imperative, possibly effectful code. The first argument is the effect itself, and the second argument is the array of dependencies.
import React, { useEffect } from 'react';

function UserProfile({ name }) {
  useEffect(() => {
    console.log('Component did mount');

    return () => {
      console.log('Component will unmount');
    };
  }, []);

  useEffect(() => {
    console.log('Name has updated');
  }, [name]);

  return <div>{name}</div>;
}

Conclusion

This version uses React hooks to manage state and lifecycle methods, and integrates the UI elements from React Native and React Native Elements :

import React, { useState, useEffect } from 'react';
import { View } from 'react-native';
import { Button, Card, Input, Avatar } from 'react-native-elements';

const UserProfile = ({ name, initialAge = 25 }) => {
  const [age, setAge] = useState(initialAge);
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');

  // Equivalent to componentDidMount and componentWillUnmount
  useEffect(() => {
    console.log('Component did mount');
    return () => {
      console.log('Component will unmount');
    };
  }, []);

  // Equivalent to componentDidUpdate for name prop
  useEffect(() => {
    console.log('Name has updated:', name);
  }, [name]);

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Avatar
        rounded
        size="large"
        source={{ uri: './assets/user-avatar.jpg' }} // Fixed path
      />
      <Card>
        <Card.Title>{name}'s Profile</Card.Title>
        <Card.Divider />
        <Input
          placeholder="Username"
          value={username}
          onChangeText={setUsername}
        />
        <Input
          placeholder="Email"
          keyboardType="email-address"
          value={email}
          onChangeText={setEmail}
        />
        <Input
          placeholder="Age"
          value={age.toString()}
          onChangeText={(text) => setAge(Number(text))}
        />
        <Button title="Update Profile" onPress={() => console.log("Profile Updated")} />
      </Card>
    </View>
  );
};

export default UserProfile;

React : the coding quest !

Creating a mobile application with React Native often involves leveraging UI frameworks to expedite development and ensure a polished user experience.

Introduction to UI Frameworks in React Native

UI frameworks provide pre-built, customizable components that can streamline the development of visually appealing and functionally rich mobile applications. They offer a wide range of components like buttons, forms, navigation bars, and more, adhering to modern design standards.

Step 1 : Setting Up Visual Studio Code and Extensions

  1. Download and Install Visual Studio Code (VS Code) : Start by downloading VS Code from the official website. It’s a powerful editor for JavaScript development, among others.
  2. Install Essential Extensions : Enhance your development experience with extensions like ESLint for code quality, Prettier for formatting, and the React Native Tools for specific React Native functionalities.

Step 2 : Installing Node.js (Version 12)

  1. Download Node.js : Ensure you have Node.js version 12 installed. You can download it from Node.js’s official website. This version is compatible with a wide range of dependencies in React Native projects.
nvm install node

Step 3: Introduction to Expo

  1. What is Expo?: Expo is a framework and platform for universal React applications. It provides a set of tools that simplify the development, build, and deployment process of React Native apps. With Expo, you can develop your app within a managed workflow, using pre-configured components and libraries.

Step 4: Installing Expo

Install Expo CLI : Use npm to install Expo CLI globally on your machine. Open your terminal and run:

   npm install -g expo-cli

Install React Native Elements:

   npm install react-native-elements

Step 5: Creating Your First Project

  1. Initialize Your Project : With Expo installed, generate your first project by executing:
   expo init MyFirstReactNativeApp
   npx create-expo-app pdf-cv
  1. Choose a Workflow : Select the “Managed workflow” template when prompted. This workflow abstracts many configurations and simplifies the development process.

Step 6 : Understanding the Metro Bundler and package.json

  1. Metro Bundler : Once the project is created, Expo uses Metro, the JavaScript bundler for React Native, to compile and serve your app’s code. You can start the Metro Bundler directly from your terminal by running expo start.
  2. package.json : This file contains your project’s dependencies and scripts. It’s crucial for managing your app’s libraries and defining commands to run, test, or build your app.

Step 7 : Running Your Project on an Android Emulator

  1. Install Android Studio : To run your app on an Android emulator, download and install Android Studio from the official website.
  2. Setup an Emulator : Inside Android Studio, use the AVD Manager to create and configure an Android virtual device.
  3. Launch Your App : With your emulator running, execute expo start, then press a in the terminal to launch your app on the Android emulator.

Step 8 : Exploring Expo Project Architecture

  1. Project Structure : An Expo project includes several key directories and files. App.js is where your app’s main component resides. The assets folder stores images and other static resources. Configuration is handled in app.json.

Step 9 : Android Emulator and Development Menu

  1. Using the Android Emulator : The emulator simulates Android devices on your computer, allowing you to test your app in a variety of device configurations without needing physical devices.
  2. Development Menu : Access additional tools and settings by shaking the virtual device or invoking the development menu through a command. This menu offers options like reloading your app, enabling hot reloading, or opening developer tools.

Choosing a UI Framework

Several UI frameworks are available for React Native, each with its own set of components and design philosophies :

  • React Native Elements : Provides a wide variety of customizable components library and ease of use.
  • NativeBase : Offers components that adhere closely to material design guidelines.
  • UI Kitten : A framework that focuses on theming and allows you to apply a global theme to your app.

Creating a Simple Application with React Native Elements

Let’s create a simple app that uses various components from React Native Elements, such as buttons, input fields, and cards, to create a user profile page.

  1. Import Components : In your main app file or a specific screen, import the necessary components from React Native Elements.
   import React from 'react';
   import { View } from 'react-native';
   import { Button, Card, Input, Avatar } from 'react-native-elements';
  1. Build the U I : Construct a simple user profile UI using the imported components.
   export default function UserProfile() {
     return (
       <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
         <Avatar
           rounded
           size="large"
           source={{
             uri: 'https://example.com/user-avatar.jpg',
           }}
         />
         <Card>
           <Card.Title>User Profile</Card.Title>
           <Card.Divider/>
           <Input placeholder="Username" />
           <Input placeholder="Email" keyboardType="email-address" />
           <Button title="Update Profile" onPress={() => console.log("Profile Updated")} />
         </Card>
       </View>
     );
   }
  1. Run Your App : Use Expo to run your app and see the UI in action.
cd pdf-cv
npx expo start

Conclusion

Incorporating a UI framework into your React Native project can greatly enhance the development process, making it faster and more efficient to build high-quality mobile applications.

React Native app for managing tasks, utilizing Expo for development and an SQL database for persistent storage

Prerequisites :

  • Basic knowledge of JavaScript and React.
  • Node.js and npm installed on your machine.
  • Expo CLI installed globally (npm install -g expo-cli).

Step 1 : Setting Up the Project Environment

  1. Initialize the Expo Project :
   expo init TaskManagerApp

Choose a template (“blank” for a minimal setup).

  1. Navigate into Your Project Directory :
   cd TaskManagerApp
  1. Install Dependencies for navigation and other utilities :
   npm install @react-navigation/native @react-navigation/stack react-native-screens react-native-safe-area-context

Step 2 : Setting Up the Database

We’ll use SQLite, which is supported out of the box by Expo and suitable for simple applications.

  1. Install Expo SQLite :
   expo install expo-sqlite
  1. Initialize the Database : Create a new file database.js in your project root. Use it to initialize the database and define functions for interacting with it.
   import * as SQLite from 'expo-sqlite';

   const db = SQLite.openDatabase('tasks.db');

   export const init = () => {
     const promise = new Promise((resolve, reject) => {
       db.transaction((tx) => {
         tx.executeSql(
           `CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY NOT NULL, title TEXT NOT NULL, done INT NOT NULL);`,
           [],
           () => {
             resolve();
           },
           (_, err) => {
             reject(err);
           }
         );
       });
     });

     return promise;
   };

Step 3: Building the UI

  1. Implement Navigation: Set up stack navigation in App.js.
   import React from 'react';
   import { NavigationContainer } from '@react-navigation/native';
   import { createStackNavigator } from '@react-navigation/stack';
   import TasksScreen from './screens/TasksScreen'; // Define this screen
   import AddTaskScreen from './screens/AddTaskScreen'; // Define this screen

   const Stack = createStackNavigator();

   function App() {
     return (
       <NavigationContainer>
         <Stack.Navigator initialRouteName="Tasks">
           <Stack.Screen name="Tasks" component={TasksScreen} />
           <Stack.Screen name="AddTask" component={AddTaskScreen} />
         </Stack.Navigator>
       </NavigationContainer>
     );
   }

   export default App;
  1. Create Screens: Implement TasksScreen and AddTaskScreen to list tasks and add new tasks, respectively.

Step 4: Interacting with the Database

// Initialize database connection
const db = SQLite.openDatabase('myAppDB', 1);

// Create tasks table if not exists
db.transaction(tx => {
  tx.executeSql(
    'CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, description TEXT, isDone INTEGER)',
    [],
    () => console.log('Tasks table created'),
    (_, error) => console.error('Error creating tasks table:', error)
  );
});

// Display tasks
db.transaction(tx => {
  tx.executeSql(
    'SELECT * FROM tasks',
    [],
    (_, { rows }) => {
      const tasks = rows._array; // Array of tasks
      // Display tasks in UI
    },
    (_, error) => console.error('Error fetching tasks:', error)
  );
});

// Add new task
const addTask = (title, description) => {
  db.transaction(tx => {
    tx.executeSql(
      'INSERT INTO tasks (title, description, isDone) VALUES (?, ?, 0)',
      [title, description],
      () => console.log('Task added successfully'),
      (_, error) => console.error('Error adding task:', error)
    );
  });
};

// Mark task as done
const markTaskAsDone = taskId => {
  db.transaction(tx => {
    tx.executeSql(
      'UPDATE tasks SET isDone = 1 WHERE id = ?',
      [taskId],
      () => console.log('Task marked as done'),
      (_, error) => console.error('Error marking task as done:', error)
    );
  });
};

// Delete task
const deleteTask = taskId => {
  db.transaction(tx => {
    tx.executeSql(
      'DELETE FROM tasks WHERE id = ?',
      [taskId],
      () => console.log('Task deleted'),
      (_, error) => console.error('Error deleting task:', error)
    );
  });
};

Step 5: Running Your App

  1. Start Your Expo Project:
   expo start
  1. Test on Devices: Use the Expo Go app on your smartphone to scan the QR code provided by Expo. Alternatively, use an Android or iOS emulator.

Conclusion

This is the basics of creating mobile applications with persistent data storage, navigation between different screens, and the utilization of Expo’s powerful ecosystem for development and testing.

Mobile App with React using Visual Studio Code and Linux

Installation: npm installs packages to your project or globally on your machine. npx executes packages from the npm registry without requiring a permanent installation.

Flexibility: npx provides a more flexible way to use and test npm packages and tools without altering your project’s setup or your global environm

Setting Up the Development Environment

  1. Install Node.js and npm: React requires Node.js to run on your machine. You can install Node.js and npm together from the Linux terminal. sudo apt update sudo apt install nodejs npm
  2. Install Visual Studio Code: VS Code is a popular code editor for React development. Install it from the official package or the Ubuntu Software Center. sudo snap install --classic code
  3. Open VS Code and install essential extensions like ESLint, Prettier, and the Reactjs code snippets for a better development experience.

Initializing the React Project

  1. Open a terminal and run the following command to create a new React app named my-app: npx create-react-app my-app
  2. Navigate into your project directory: cd my-app
  3. Start the development server to see your app in action: npm start

Implementing Context API

The Context API allows you to share state across the entire app easily, which is especially useful for themes, user information, etc., without prop drilling.

Create a Context: In your src directory, create a new file named ThemeContext.js.

import React from 'react';

const ThemeContext = React.createContext();

export default ThemeContext;

Provide Context Value: To use the Context, you must wrap your component tree with the Context Provider and pass a value to it. Modify App.js to include the ThemeContext.Provider.

import React from 'react';
import './App.css';
import ThemeContext from './ThemeContext';

function App() {
  return (
    <ThemeContext.Provider value={{ theme: 'dark' }}>
      {/* Rest of your app components go here */}
    </ThemeContext.Provider>
  );
}

export default App;

Consume Context: Any child component in the component tree can now consume the Context value.

import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';

function ThemeToggler() {
  const { theme, setTheme } = useContext(ThemeContext);

  return (
    <button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
      Toggle Theme
    </button>
  );
}

export default ThemeToggler;

Building a Mobile App with React Native and Expo

Developing a mobile application with React Native provides a seamless way to create cross-platform apps using JavaScript. This section of the article will guide you through the process of using Expo, a framework and platform for universal React applications, which simplifies the development and testing of React Native apps.

Step 1: Setting Up Your Development Environment

Before diving into coding, ensure your environment is prepared for React Native development with Expo.

  • Install Node.js: Ensure Node.js is installed on your system. It’s required for running the Expo CLI (Command Line Interface).
  • Install Expo CLI: Run npm install -g expo-cli in your terminal to install the Expo CLI globally.
  • Expo Go App: For real-device testing, download the Expo Go app from your device’s app store.

Step 2: Creating Your React Native Project with Expo

  1. Initialize the Project: In your terminal, navigate to your workspace and run expo init MyReactNativeApp to create a new React Native project. Choose a template from the options provided.
  2. Start the Development Server: Navigate into your project folder using cd MyReactNativeApp and start the project by running expo start. This command will open a new tab in your default web browser, displaying the Expo developer tools.

Step 3: Building Components and Implementing Navigation

With the project set up, you’ll begin developing your application’s UI and logic.

  • Creating Components: Organize your application by creating separate components for each part of your UI. Use functional components and React Hooks for state management and lifecycle methods.
  import React from 'react';
  import { Text, View } from 'react-native';

  const CustomComponent = () => (
    <View>
      <Text>Hello, React Native!</Text>
    </View>
  );

  export default CustomComponent;
  • Implementing Navigation: Install React Navigation in your Expo project to enable navigation between different screens.
  npm install @react-navigation/native @react-navigation/stack
  expo install react-native-screens react-native-safe-area-context

Set up a Stack Navigator as the root navigator for your app. This allows you to define a series of screens that users can navigate through.

  import { NavigationContainer } from '@react-navigation/native';
  import { createStackNavigator } from '@react-navigation/stack';
  import HomeScreen from './HomeScreen';
  import DetailsScreen from './DetailsScreen';

  const Stack = createStackNavigator();

  function AppNavigator() {
    return (
      <NavigationContainer>
        <Stack.Navigator initialRouteName="Home">
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Details" component={DetailsScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }

Step 4: Testing and Debugging

  • Testing on Devices: Use the Expo Go app to scan the QR code displayed in your terminal or Expo developer tools. This allows you to test the app on real devices.
  • Debugging: Take advantage of the debugging tools provided by Expo and React Native. Use console.log, React Developer Tools, and the remote debugger to trace and fix issues.

Conclusion

This article has guided you through setting up your development environment, creating a new React Native project with Expo, building components, and implementing navigation.

The Power of ‘No’

Combien de fois dites-vous « non » à des choses qui pourraient interférer avec vos objectifs ?

Every time we say "no" to a request or an opportunity that doesn’t align with our goals, we’re essentially making room for those that do. This principle is crucial in the fast-evolving tech world. The selection of technologies for our projects should resonate with scalability, or maintainability.

Understanding the Significance of ‘No’ in Professional Growth, Node.js LTS

Node.js, a runtime environment based on Chrome’s V8 JavaScript engine, facilitates the development of fast and scalable network applications. Its Long-Term Support (LTS) versions, offer stability and extended support. This makes Node.js LTS an ideal choice for developers looking to build reliable and maintainable applications.

More about Node.js LTS

The Frontend Library for Interactive UIs : React.js

React.js stands out as a declarative, efficient, and flexible JavaScript library for building user interfaces. It enables developers to create large web applications that can change data without reloading the page, promising a smooth user experience.

Learn more about React.js

A Powerful Combination

Combining Node.js LTS and React.js allows developers to build full-stack JavaScript applications with ease. Here’s a simple workflow:

  1. Backend with Node.js LTS: Set up a server using Express, a Node.js framework, to handle API requests.
  2. Frontend with React.js: Create interactive UIs that communicate with the backend server for dynamic content.

This synergy enables the development of fast, responsive, and maintainable web applications.

Backend: Node.js with Express

Assuming Node.js is installed and the express package is added to your project, set up a basic Express server that serves a static list of tasks.

File: server.js

const express = require('express');
const app = express();
const port = 3001;

// Sample data
const tasks = [
  { id: 1, title: 'Learn Node.js', completed: false },
  { id: 2, title: 'Practice React.js', completed: false },
  { id: 3, title: 'Build a full-stack app', completed: false }
];

// Middleware to allow cross-origin requests
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

// A simple API to fetch tasks
app.get('/api/tasks', (req, res) => {
  res.json(tasks);
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

To run this server, execute node server.js in your terminal,

Frontend: React.js

Now, create a simple React component that fetches and displays these tasks.

File: TasksComponent.js

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

function TasksComponent() {
  const [tasks, setTasks] = useState([]);

  // Fetch tasks from the backend on component mount
  useEffect(() => {
    fetch('http://localhost:3001/api/tasks')
      .then(response => response.json())
      .then(data => setTasks(data))
      .catch(error => console.error('Error fetching tasks:', error));
  }, []); // Empty dependency array means this effect runs once on mount

  return (
    <div>
      <h2>Tasks List</h2>
      <ul>
        {tasks.map(task => (
          <li key={task.id}>
            {task.title} - {task.completed ? 'Done' : 'Pending'}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default TasksComponent;

To integrate this component into a React application, you would include it in your app’s component tree, usually in the App.js file. Make sure your React app is running on a different port (the default create-react-app port is 3000) to avoid conflicts with the backend server.

Running the Full-Stack App

  1. Start the backend server (node server.js).
  2. Run the React frontend app (typically with npm start or yarn start in the create-react-app scaffold).

DOM Schema with Emoji 🌐 ➡️ 📝

Consider a simple DOM schema representing a web app structure:

  • 🌐 Root: The entry point of the application.
  • 📝 Component 1: A functional component for handling user inputs.
  • 📄 Component 2: A class component for displaying data fetched from the Node.js server.

Conclusion

Fetching Data with React.js and Displaying It

// A simple React function to fetch data from a Node.js backend
async function fetchData() {
  const response = await fetch('http://your-node-server.com/api/data');
  const data = await response.json();
  console.log(data);
}

Saying "no" to technologies that don’t align with our goals allows us to focus on tools that do, like the powerful combination of Node.js LTS and React.js. This approach not only aids in achieving our project objectives but also in realizing our broader goal of becoming a successful developer.

Modern Web Development

Quel est le meilleur compliment que vous ayez reçu ?

Styling in React with SCSS

SCSS, or Sassy CSS, offers a more dynamic and powerful approach to styling in conjunction with React, it allows for modular and reusable style sheets that can enhance the visual hierarchy and aesthetics of web applications.

  • Import these styles directly into your React components : Use node-sass or dart-sass in your React project to compile SCSS files into CSS.

Learn More about SCSS

React Router

React Router plays a pivotal role in developing single-page applications () by managing the navigation between different views without refreshing the page.

  • Usage: Define routes using <Route> components within a <Router> to map paths to components.

React Router Documentation

Maintenance and Best Practices

Maintaining a React application involves regular dependency updates, code refactoring for performance optimization, and adherence to best practices such as code splitting and the judicious use of PureComponent keeps your application scalable and maintainable.

Dependencies in React projects are managed through package.json. Keeping these dependencies up to date is crucial for security, performance, and accessing new features.

A simple npm command to update all your project’s dependencies to their latest versions :

npm update

Resource :

Code Refactoring for Performance Optimization

Refactoring your React code can significantly impact performance, especially for large and complex applications. This could involve breaking down large components into smaller, more manageable ones, optimizing re-renders with React.memo or useMemo, and ensuring that components only update when necessary.

const MyComponent = React.memo(function MyComponent(props) {
/* render using props */
});

React.memo is a higher order component that tells React to memoize a component. It only rerenders the component if the props change.

Resource:

Code Splitting

Code splitting is a technique that allows you to split your code into smaller chunks which you then load on demand. React supports code splitting via dynamic import().

Example: Using dynamic import() for Code Splittingimport React, { Suspense, lazy } from 'react'; const OtherComponent = lazy(() => import('./OtherComponent')); function MyComponent() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense> </div> ); }

Resource:

Using PureComponent Wisely

PureComponent is useful for optimizing class components that re-render frequently. It implements shouldComponentUpdate with a shallow prop and state comparison. This means the component only updates if there’s a change in props or state, preventing unnecessary updates.

Example: Using PureComponentimport React, { PureComponent } from 'react'; class MyComponent extends PureComponent { render() { return <div>{this.props.myProp}</div>; } }

Resource:

Understanding React through Algorithms

React’s declarative nature contrasts with the imperative approach seen in traditional algorithms. An algorithm in React might involve setting state based on user input or API responses, showcasing React’s reactive paradigm.

Algorithm Example: Dynamic List Rendering in App.js

import React, { useState, useEffect } from ‘react’;

function App() {
const [items, setItems] = useState([]);

useEffect(() => {
// Imagine fetching data from an API here
setItems([{ id: 1, text: ‘Learn React’ }, { id: 2, text: ‘Build Projects’ }]);
}, []);

return (
<div>
{items.map(item => (
<div key={item.id}>{item.text}</div>
))}
</div>
);
}

export default App;

Reflecting on Compliments

Transitioning from the technical to the personal, the finest compliment I’ve ever received was about my ability to simplify complex concepts, making them accessible to others. This feedback, beyond its immediate warmth, underscored the importance of clear communication in education and knowledge sharing. It’s a principle that guides both my teaching and writing, especially in articles like this one.


To illustrate an improved version of a React App.js file for a pizza-related application, let’s craft a functional component that showcases a simple pizza menu. This component will import necessary React features, display a list of pizzas, and include a basic interaction to select a pizza. We’ll also touch on organizing this into a scalable structure by importing a hypothetical PizzaMenu component.

Step 1: Set Up Your Project

Ensure you have a React environment set up. If you’re starting from scratch, the easiest way is to use Create React App:npx create-react-app pizza-app cd pizza-app

Step 2: Install Necessary Packages

While this example may not require additional packages, remember that real-world applications might need libraries such as react-router-dom for routing or sass for SCSS styling.

Step 3: Define the PizzaMenu Component

Before we dive into App.js, let’s assume you have a PizzaMenu component in a separate file (PizzaMenu.js). This component could look something like this:

File: PizzaMenu.js

import React from ‘react’;

const PizzaMenu = ({ pizzas, onSelectPizza }) => (
<div>
<h2>Choose Your Pizza</h2>
<ul>
{pizzas.map(pizza => (
<li key={pizza.id} onClick={() => onSelectPizza(pizza)}>
{pizza.name} – {pizza.ingredients.join(‘, ‘)}
</li>
))}
</ul>
</div>
);

export default PizzaMenu;

Step 4: Implement App.js with PizzaMenu Component

Now, let’s refactor App.js to include the PizzaMenu component, demonstrating a functional component structure with hooks for state management.

File: App.js

import React, { useState } from ‘react’;
import PizzaMenu from ‘./PizzaMenu’; // Import the PizzaMenu component

const initialPizzas = [
{ id: 1, name: ‘Margherita’, ingredients: [‘tomato’, ‘mozzarella’, ‘basil’] },
{ id: 2, name: ‘Pepperoni’, ingredients: [‘tomato’, ‘mozzarella’, ‘pepperoni’] },
{ id: 3, name: ‘Four Seasons’, ingredients: [‘tomato’, ‘mozzarella’, ‘mushrooms’, ‘ham’, ‘artichokes’, ‘olives’, ‘oregano’] },
];

function App() {
const [selectedPizza, setSelectedPizza] = useState(null);

const handleSelectPizza = pizza => {
setSelectedPizza(pizza);
console.log(`Selected Pizza: ${pizza.name}`);
};

return (
<div className=”App”>
<h1>Pizza Selection</h1>
<PizzaMenu pizzas={initialPizzas} onSelectPizza={handleSelectPizza} />
{selectedPizza && (
<div>
<h3>You selected: {selectedPizza.name}</h3>
<p>Ingredients: {selectedPizza.ingredients.join(‘, ‘)}</p>
</div>
)}
</div>
);
}

export default App;

This App.js demonstrates a clean, functional approach to building a React application. It imports a PizzaMenu component, uses hooks for state management, and handles user interactions in a straightforward manner.

Hooks are a feature introduced in React 16.8 that allow you to use state and other React features without writing a class. They enable functional components to have access to stateful logic and lifecycle features that were previously only possible with class components. Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.

Commonly Used React Hooks

  • useState: This hook allows you to add React state to functional components. When you call it, you receive a pair: the current state value and a function that lets you update it.

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

  • useEffect: This hook lets you perform side effects in functional components. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, unified into a single API.

useEffect(() => { // Code to run on component mount or update return () => { // Cleanup code, similar to componentWillUnmount }; }, [/* dependencies */]);

  • useContext: This hook allows you to access the value of a React context. It makes it easier to consume the context value in functional components without relying on the Consumer component.

const value = useContext(MyContext);

  • useReducer: An alternative to useState, ideal for managing state logic that involves multiple sub-values or when the next state depends on the previous one. It also makes transitioning to Redux easier if needed.

const [state, dispatch] = useReducer(reducer, initialState);

  • useCallback: Returns a memoized callback function. This is useful for passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);

  • useMemo: Returns a memoized value. It only recalculates the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

  • useRef: Returns a mutable ref object whose .current property is initialized to the passed argument. It can be used to store a mutable value that does not cause re-render when updated.

const myRef = useRef(initialValue);

  • useLayoutEffect: It has the same signature as useEffect, but it fires synchronously after all DOM mutations. Use it to read layout from the DOM and re-render synchronously.

Benefits of Hooks

  • Simplified Code: Hooks allow you to use more of React’s features without classes, which can make your code cleaner and easier to understand.
  • Reusability: Custom hooks can encapsulate stateful logic and be shared across components, promoting code reuse.
  • Composition: Hooks offer a more powerful and flexible way to compose software logic compared to patterns like higher-order components (HOCs) and render props.

By providing a more direct API to React’s features, hooks embrace functional programming principles and significantly simplify component logic, making it more predictable and easier to manage.

Newer posts »

© 2024 Kvnbbg.fr

Theme by Anders NorénUp ↑

Verified by MonsterInsights