React JS E-BooK
React JS E-BooK
React is a JavaScript library for building user interfaces, primarily for web applications. It was
developed by Facebook and released as open-source in 2013. React focuses on creating reusable UI
components and managing their state efficiently, making it popular for building complex and
interactive user interfaces.
Introduction
React is a popular JavaScript library for building user interfaces, particularly for single-page
applications and large-scale web applications. Developed by Facebook, React allows developers to
create interactive and dynamic UI components efficiently. Here's an introduction to React and its key
concepts:
1. Component-Based Architecture:
React is built around the concept of reusable UI components. A React application is composed
of multiple components, each responsible for rendering a part of the UI.
Components are self-contained and can be composed together to build complex UIs. They
encapsulate both the UI elements and the logic associated with them.
2. Virtual DOM:
React uses a virtual DOM (Document Object Model) to efficiently update the UI. The virtual
DOM is a lightweight representation of the actual DOM, maintained by React.
When the state of a component changes, React compares the virtual DOM with the previous
version and only updates the necessary parts of the actual DOM. This approach improves
performance by minimizing DOM manipulation.
5. Declarative Syntax:
React promotes a declarative approach to building UIs, where you describe what you want the
UI to look like based on the current state, rather than imperatively specifying how to change
the UI in response to user actions.
Declarative code is often more concise, easier to understand, and less error-prone than
imperative code.
6. React Hooks:
Introduced in React 16.8, hooks are functions that allow you to use state and other React
features in function components, instead of having to use class components.
Hooks provide a more straightforward and composable way to manage component state, side
effects, and lifecycle events.
7. Reusable Components:
React encourages the development of reusable and composable UI components, which can be
shared and reused across different parts of the application.
This modular approach promotes code reusability, maintainability, and scalability, as
components can be easily composed to create complex UIs.
React's simplicity, performance, and robust ecosystem of libraries and tools have made it a
popular choice for front-end development. Whether you're building a simple web application
or a complex enterprise-level application, React provides the flexibility and power to create
modern, interactive user interfaces.
React Getting Started
To get started with React, you'll need to set up your development environment and create a new React
project. Here's a step-by-step guide to help you get started:
Replace my-react-app with the name you want for your project. This command will create a
new directory with the specified name and set up a basic React project structure for you.
cd my-react-app
npm start
This command will start the development server and open your default web browser to view
your React application running locally.
my-react-app/
├── node_modules/ # Dependencies installed via npm
├── public/ # Public assets and index.html
├── src/ # React application source code
│ ├── App.css # CSS styles for App component
│ ├── App.js # Main component
│ ├── App.test.js # Test file
│ ├── index.css # Global styles
│ ├── index.js # Entry point
│ └── logo.svg # Sample SVG logo
├── .gitignore # Gitignore file
├── package-lock.json # npm package lock file
├── package.json # npm package configuration
└── README.md # Project readme file
The src directory contains the main source code of your React application. The App.js file is
the main component, and it's where you'll start building your application.
7. Learn React:
React has a rich ecosystem of documentation, tutorials, and community resources to help you
learn and master the library.
The official React documentation is a great place to start: React Documentation.
By following these steps, you'll have a basic React project set up and running locally on your
development machine. You can then begin exploring React's features and building your own
applications.
Upgrade React
To upgrade an existing React project to a newer version of React, you'll need to follow these general
steps:
Replace latest with the specific version you want to upgrade to if you're not using the latest
version.
9. Commit Changes:
Once you've completed the upgrade process and tested your application, commit your changes
to version control (e.g., Git) to track the updates and make it easier to roll back if necessary.
1. Arrow Functions:
Arrow functions provide a more concise syntax for defining functions, especially for inline
callbacks and event handlers.
Example:
2. Classes:
ES6 classes offer a more structured way to define React components, replacing the older
createClass method.
Example:
3. Template Literals:
Template literals allow for easier string interpolation and multi-line strings in JSX templates.
Example:
4. Destructuring:
Destructuring assignment simplifies the extraction of values from objects and arrays, often
used with props and state.
Example:
5. Spread Syntax:
The spread syntax ( ...) allows for the expansion of iterable objects like arrays and objects,
commonly used for passing props or merging objects.
Example:
6. Modules:
ES6 introduced a standardized module system ( import and export keywords), which is
commonly used for organizing and importing/exporting React components and utilities.
Example:
// Component.js
import React from 'react';
const MyComponent = () => <h1>Hello, World!</h1>;
export default MyComponent;
// App.js
import React from 'react';
import MyComponent from './Component';
let count = 0;
const maxCount = 10;
These are just a few examples of how ES6 features are commonly used in React development.
Leveraging these features can lead to cleaner, more expressive, and more maintainable React code.
React ES6 Classes
In React, ES6 classes are commonly used to define components. ES6 classes provide a more
structured and familiar syntax for defining components compared to the older createClass method.
Here's how ES6 classes are used to define React components:
1. Class Declaration:
You can define a React component by creating a class that extends React.Component.
The class must have a render() method that returns the component's JSX structure.
Example:
javascriptCopy code
import React from 'react'; class MyComponent extends React.Component { render() { return
<h1>Hello, World!</h1>; } } export default MyComponent;
3. Props:
Props are passed to the component as parameters to the constructor and are accessible using
this.props.
Example:
4. Lifecycle Methods:
React class components have lifecycle methods that allow you to hook into component
lifecycle events, such as mounting, updating, and unmounting.
Example:
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <h1>Hello, World!</h1>;
}
}
Using ES6 classes to define React components offers a more modern and structured approach to
building UIs, making it easier to manage component state, lifecycle events, and code organization.
React ES6 Arrow Functions
In React, ES6 arrow functions are commonly used for defining functional components, event
handlers, and callback functions. Arrow functions provide a concise and more readable syntax
compared to traditional function expressions, especially for inline functions and callbacks. Here's how
ES6 arrow functions are used in React:
1. Functional Components:
Arrow functions can be used to define functional components, which are stateless components
that only render UI based on props.
Example:
4. Class Methods:
Arrow functions can be used to define class methods within React component classes. When
using arrow functions for class methods, you don't need to manually bind this in the
constructor.
Example:
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<h1>Counter: {this.state.count}</h1>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
1. Const Variables:
const is used to declare variables whose values cannot be reassigned after initialization.
It's commonly used for defining variables that represent immutable values or references to
components.
Example:
return <h1>{message}</h1>;
};
2. Let Variables:
let is used to declare variables that can be reassigned within the block scope in which they are
defined.
It's commonly used for defining variables that may change their values during the
component's lifecycle.
Example:
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={handleClick}>Increment</button>
</div>
);
};
// Other code...
};
4. Block Scoping:
Both const and let variables are block-scoped, meaning they are only accessible within the
block (enclosed by curly braces) in which they are defined.
This helps prevent variable hoisting issues and makes code easier to understand and reason
about.
Example:
Using const and let variables in React components helps create more predictable and maintainable
code, ensuring that variables are scoped appropriately and their values are controlled effectively
throughout the component's lifecycle.
React ES6 Array Methods
In React, ES6 array methods are commonly used for manipulating arrays of data within components.
These methods provide powerful and concise ways to iterate, filter, map, and reduce arrays, making it
easier to work with data in React components. Here are some commonly used ES6 array methods in
React:
1. map():
The map() method creates a new array by applying a function to each element of the original
array.
It's commonly used for rendering lists of data in React components.
Example:
return (
<ul>
{numbers.map((number) => (
<li key={number}>{number}</li>
))}
</ul>
);
};
2. filter():
The filter() method creates a new array with all elements that pass a certain condition
specified by a callback function.
It's commonly used for filtering data based on specific criteria.
Example:
3. reduce():
The reduce() method applies a function against an accumulator and each element in the array
(from left to right) to reduce it to a single value.
It's commonly used for aggregating data or performing calculations on arrays.
Example:
4. find():
The find() method returns the value of the first element in the array that satisfies a provided
testing function.
It's commonly used for finding a specific item in an array.
Example:
These are just a few examples of how ES6 array methods can be used in React components to
manipulate and process arrays of data efficiently. By leveraging these methods, you can write cleaner
and more expressive code when working with arrays in your React applications.
React ES6 Destructuring
Destructuring in ES6 allows you to extract values from objects or arrays and assign them to variables
in a more concise and readable way. In React, destructuring is commonly used for accessing props,
state, and other objects within functional components. Here's how destructuring is used in React ES6:
1. Destructuring Props:
In functional components, props are passed as an object parameter. Destructuring allows you
to extract individual props into separate variables for easier access.
Example:
2. Destructuring State:
In class components, state is accessed via this.state. Destructuring can be used within the
render() method to extract state values into variables.
Example:
render() {
const { count } = this.state;
return <h1>Count: {count}</h1>;
}
}
3. Destructuring Arrays:
Destructuring can also be used with arrays to extract values based on their positions.
Example:
5. Default Values:
Destructuring allows you to set default values for variables in case the destructured value is
undefined.
Example:
1. Copying Arrays:
The spread operator can be used to create a shallow copy of an array. This is useful when you
want to modify an array without mutating the original.
Example:
2. Merging Arrays:
The spread operator can be used to merge two or more arrays into a single array.
Example:
3. Copying Objects:
The spread operator can be used to create a shallow copy of an object. This is useful when
you want to modify an object without mutating the original.
Example:
4. Merging Objects:
The spread operator can be used to merge two or more objects into a single object.
Example:
const object1 = { name: 'John' };
const object2 = { age: 30 };
const mergedObject = { ...object1, ...object2 };
5. Passing Props:
In React, the spread operator is commonly used to pass props to child components
dynamically. This allows for cleaner and more concise code.
Example:
6. Updating State:
When updating state in React, the spread operator is often used to merge the existing state
with the new state.
Example:
this.setState({
...this.state,
count: this.state.count + 1
});
The spread operator is a versatile tool in React development, providing a concise and efficient way to
work with arrays and objects. It helps simplify code and improves readability, making it a valuable
feature in React components.
React ES6 Modules
In React, ES6 modules are used to organize and manage the codebase by breaking it down into
smaller, reusable modules. ES6 modules allow you to export functions, classes, or variables from one
module and import them into another module where they are needed. This modular approach helps
improve code maintainability, reusability, and scalability. Here's how ES6 modules are used in React:
// utils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
2. Named Exports:
You can have multiple named exports in a single module by using the export keyword before
each declaration.
Example:
// utils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
3. Default Export:
In addition to named exports, you can also have a default export in a module using the export
default syntax.
Example:
// utils.js
const multiply = (a, b) => a * b;
export default multiply;
// App.js
import { add, subtract } from './utils';
import multiply from './utils';
5. Renaming Imports:
You can rename named imports by using the as keyword followed by the new name.
Example:
// App.js
import { add as addition, subtract as subtraction } from './utils';
// App.js
import * as utils from './utils';
ES6 modules provide a clean and efficient way to organize code in React applications, allowing for
better separation of concerns and improved code maintainability. By leveraging modular architecture,
you can easily manage dependencies, reuse code, and scale your React application effectively.
React ES6 Ternary Operator
In React, the ES6 ternary operator ( ? :) is commonly used for conditional rendering and conditional
logic within JSX expressions. The ternary operator provides a concise and readable way to
conditionally render different elements or values based on certain conditions. Here's how the ternary
operator is used in React:
1. Conditional Rendering:
The ternary operator is often used to conditionally render different JSX elements based on a
condition.
Example:
2. Conditional Styling:
You can use the ternary operator to conditionally apply CSS classes or inline styles based on
certain conditions.
Example:
The ternary operator is a powerful tool for writing conditional logic and conditional rendering in
React components. It helps keep the JSX code clean, concise, and readable, making it easier to
understand and maintain your React applications.
React Render HTML
In React, you can render HTML elements using JSX syntax. JSX allows you to write HTML-like code
directly within your JavaScript files, which gets compiled into regular JavaScript code that React can
understand and render. Here's how you can render HTML elements in a React component:
Example:
In the example above, we've defined a functional component MyComponent that returns JSX
containing various HTML elements such as div, h1, p, and ul with li elements. When this component
is rendered, React will create a corresponding DOM structure based on the JSX elements.
You can also embed JavaScript expressions within JSX by wrapping them in curly braces {}. This
allows you to dynamically generate content based on variables or props:
Example:
return (
<div>
<h1>{greeting}</h1>
<p>{name} is learning React.</p>
</div>
);
};
In this example, the greeting variable is dynamically generated using the name variable and
embedded within the JSX code.
Remember that JSX is not HTML, even though it looks very similar. JSX is a syntax extension for
JavaScript, and React components written in JSX are transformed into regular JavaScript function
calls behind the scenes. This is why JSX allows you to write HTML-like code within your JavaScript
files.
React JSX
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code
within your JavaScript files. It's commonly used with React to describe what the UI should look like.
JSX makes React components more readable and easier to write by combining HTML-like syntax
with JavaScript expressions. Here are some key points about JSX:
1. HTML-Like Syntax:
JSX looks similar to HTML but is actually closer to JavaScript. It allows you to write HTML
elements and attributes directly within your JavaScript code.
Example:
2. JavaScript Expressions:
JSX allows you to embed JavaScript expressions within curly braces {}. This allows you to
dynamically generate content, compute values, or reference variables within JSX.
Example:
6. Multiline JSX:
JSX expressions can span multiple lines. However, if the JSX expression is multiline, it
should be wrapped in parentheses () to avoid automatic semicolon insertion issues.
Example:
const element = (
<div>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</div>
);
JSX simplifies the process of creating and working with React components by providing a familiar
HTML-like syntax combined with the expressive power of JavaScript. It's an essential part of writing
React applications and is widely adopted in the React ecosystem.
React Components
In React, components are the building blocks of a user interface. They are reusable, self-contained
pieces of UI that encapsulate a specific functionality or visual aspect. React applications are typically
composed of multiple components, each responsible for rendering a part of the UI. Components can
be either functional components or class components. Here's an overview of React components:
1. Functional Components:
Functional components are simple JavaScript functions that accept props as arguments and
return JSX to describe what the UI should look like.
They are preferred for presentational components that are mainly concerned with rendering
UI based on props.
Example:
2. Class Components:
Class components are ES6 classes that extend React.Component and have a render() method
to return JSX.
They have additional features such as state and lifecycle methods, making them suitable for
more complex components.
Example:
render() {
return <h1>Count: {this.state.count}</h1>;
}
}
export default Counter;
3. Props:
Props (short for properties) are used to pass data from parent components to child
components. They are immutable and are passed down the component tree.
Example:
// Parent component
<Greeting name="John" />
// Child component
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
4. State:
State is a data structure that represents the internal state of a component. It is mutable and can
be updated using setState() method.
State is managed internally within a component and is not accessible from outside.
Example:
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
5. Lifecycle Methods:
Class components have lifecycle methods that allow you to hook into various stages of a
component's lifecycle, such as mounting, updating, and unmounting.
Example:
componentDidUpdate(prevProps, prevState) {
// Called after the component updates
}
componentWillUnmount() {
// Called before the component is unmounted
}
render() {
return <h1>Hello, World!</h1>;
}
}
React components allow you to break down your UI into smaller, reusable pieces, making your code
more modular, maintainable, and easier to reason about. Components are at the core of React's
declarative and composable nature.
React Class Components
React class components are ES6 classes that extend React.Component and have a render() method.
They are used to define components with more complex logic, state management, and lifecycle
methods. Class components are typically used when you need to manage state or use lifecycle
methods. Here's how you can create and use class components in React:
Example:
2. Adding State:
Class components can have state, which allows them to manage data that can change over
time.
State is initialized in the constructor using this.state and can be accessed using
this.state.
Example:
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
3. Handling Events:
Class components can handle events by passing event handlers as props to JSX elements.
Inside event handlers, you can update the component's state using this.setState().
Example:
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <h1>Hello, World!</h1>;
}
}
Class components are powerful and provide more features compared to functional components, such
as state management and lifecycle methods. However, with the introduction of React hooks,
functional components have become more capable and are now the preferred way of writing
components in React.
React Props
In React, props (short for properties) are a way of passing data from parent components to child
components. Props allow you to customize and configure child components by providing them with
data and behavior. Props are immutable, meaning that child components cannot modify the props
passed to them. Here's how you can work with props in React:
1. Passing Props:
You can pass props to a child component by adding attributes to the component's JSX tag.
These attributes represent the data or behavior you want to pass.
Example:
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
2. Accessing Props:
Inside the child component, you can access the props passed from the parent component via
the function argument.
Example:
// ChildComponent.js
import React from 'react';
3. Destructuring Props:
You can use object destructuring to extract individual props from the props object for easier
access.
Example:
// ChildComponent.js
import React from 'react';
4. Default Props:
You can specify default values for props using the defaultProps property. If a prop is not
provided, React will use the default value.
Example:
// ChildComponent.js
import React from 'react';
ChildComponent.defaultProps = {
name: 'Anonymous',
age: 18
};
2. Event Object:
React wraps the native DOM events in its own synthetic event system to ensure consistent
behavior across different browsers.
You can access the event object passed to event handlers as the first argument.
Example:
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
};
4. Passing Parameters:
If you need to pass additional parameters to an event handler, you can use an arrow function
or Function.prototype.bind.
Example with arrow function:
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}
React's event handling system allows you to create interactive and responsive user interfaces by
handling user interactions effectively. By following the JSX syntax and React's event system, you can
easily manage events and build dynamic UIs in your React applications.
React Conditional Rendering
Conditional rendering in React refers to the process of rendering different content or components
based on certain conditions. It allows you to control what is displayed to the user based on the current
state or props of your components. There are several ways to perform conditional rendering in React:
Example:
Conditional rendering allows you to create dynamic and responsive user interfaces in your React
applications. By controlling what is rendered based on specific conditions, you can provide a tailored
user experience and handle different scenarios effectively. Choose the approach that best suits your
use case and enhances the readability and maintainability of your code.
React Lists
In React, lists are used to render a collection of elements dynamically. Lists are commonly used when
you have an array of data and you want to render a component for each item in the array. React
provides a simple and efficient way to render lists using the map() method. Here's how you can work
with lists in React:
Lists are a fundamental part of building dynamic and interactive user interfaces in React. By
efficiently rendering collections of data, you can create flexible and reusable components that can
adapt to different data sets and user inputs. When working with lists in React, remember to assign a
unique key to each list item and leverage the power of map() for rendering.
React Forms
In React, forms are used to collect and handle user input. React provides a way to manage form data
and handle form submission efficiently using controlled components. Controlled components keep the
form data in the component's state and update it via event handlers. Here's how you can work with
forms in React:
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
placeholder="Username"
/>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
placeholder="Password"
/>
<button type="submit">Submit</button>
</form>
);
};
2. Form Submission:
Handle form submission by preventing the default behavior of the form submission event and
performing necessary actions, such as sending data to a server or processing it locally.
Example:
5. Using Refs:
Use refs to interact with form elements directly, such as focusing an input field or accessing
its value imperatively.
Example:
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={inputRef} />
<button type="submit">Submit</button>
</form>
);
};
React forms provide a flexible and efficient way to handle user input and create interactive user
interfaces. By using controlled components, form validation, and other techniques, you can build
robust and user-friendly forms in your React applications.
React Router
React Router is a popular library for handling navigation in React applications. It allows you to define
routes and associate them with specific components, enabling declarative routing in your application.
With React Router, you can implement features like nested routes, route parameters, and
programmatic navigation.
Here's a basic example of how to use React Router in a React application:
1. Installation:
First, you need to install React Router in your project. You can do this using npm or yarn:
Example:
or
2. Basic Setup:
Next, you'll set up routing in your application. Typically, you'll wrap your entire application in
a BrowserRouter component, which provides the routing context for your application.
Example:
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
3. Defining Routes:
Now, you can define routes for your application using the Route component. Each Route
component maps a URL path to a specific component that should be rendered when the path
matches.
Example:
// App.js
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import NotFound from './NotFound';
// Home.js
import React from 'react';
import { Link } from 'react-router-dom';
Example:
// About.js
import React from 'react';
import { Link } from 'react-router-dom';
// NotFound.js
import React from 'react';
That's a basic setup of React Router in a React application. You can explore more advanced features
like nested routes, route parameters, and route guards as you build more complex applications.
React Memo
React.memo is a higher-order component (HOC) provided by React that memoizes the rendering of a
functional component, preventing unnecessary re-renders. It's similar to the PureComponent class for
class components, but it's used for functional components. Memoization is a technique to optimize
rendering performance by caching the result of a function call based on its input parameters.
Here's how you can use React.memo:
Example:
When you wrap a functional component with React.memo, React will memoize the component based
on its props. If the props of the component remain the same between renders, React will reuse the
memoized version of the component and skip re-rendering, improving performance. However, if the
props change, React will re-render the component as usual.
Here are some important points to note about React.memo:
1. Shallow Comparison:
React.memo performs a shallow comparison of the props. It checks if the new props are
shallowly equal to the previous props using Object.is. If the props are shallowly equal, React
reuses the memoized component; otherwise, it re-renders the component.
2. Pure Functional Components:
React.memo is intended for pure functional components, meaning that they don't have any
side effects and their output is solely determined by their props.
3. Custom Comparison Function:
You can also provide a custom comparison function as the second argument to React.memo
to control when the component should re-render based on the props. This can be useful when
you need more control over the comparison logic.
4. Memoization Caveats:
Memoization is beneficial for optimizing performance in certain scenarios, but it's not always
necessary or beneficial. Be cautious when using React.memo and ensure that it's providing a
measurable performance improvement in your application.
Here's an example of using React.memo with a custom comparison function:
Example:
In this example, the component will only re-render if the id prop changes between renders, as
determined by the custom comparison function.
Styling React Using CSS
Styling React components using CSS is a common practice and can be achieved in several ways. Here
are some methods to style React components using CSS:
// Button.js
import React from 'react';
import './Button.css'; // Import CSS file
CSS code:
<style>
/* Button.css */
.button {
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
</style>
2. CSS-in-JS Libraries:
CSS-in-JS libraries allow you to write CSS directly inside your JavaScript or JSX files.
Popular CSS-in-JS libraries include styled-components, emotion, and CSS Modules. These
libraries offer various features such as scoped styles, dynamic styles, and theming.
Example using styled-components:
// Button.js
import React from 'react';
import styled from 'styled-components';
3. Inline Styles:
React allows you to apply styles directly to JSX elements using inline styles. Inline styles are
defined as JavaScript objects where keys represent CSS properties and values represent their
respective values.
Example:
// Button.js
import React from 'react';
<style>
// Button.scss
.button {
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
</style>
jsxCopy code:
// Button.js
import React from 'react';
import './Button.scss'; // Import Sass file
Choose the method that best fits your project requirements and preferences. Each method has its own
advantages and use cases, so feel free to experiment and find the one that works best for you.
Styling React Using Sass
To style React components using Sass (Syntactically Awesome Style Sheets), you can follow these
steps:
1. Install Sass:
First, you need to have Sass installed in your project. You can install Sass using npm or yarn:
Example:
or
csharp code:
<style>
// Button.scss
.button {
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
</style>
<style>
// variables.scss
$primary-color: #007bff;
// Button.scss
@import 'variables';
.button {
background-color: $primary-color;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
&:hover {
background-color: darken($primary-color, 10%);
}
}
</style>
By following these steps, you can easily style your React components using Sass, taking advantage of
its features to write more modular and maintainable stylesheets. Remember to compile your Sass files
into regular CSS files using a build tool like webpack or parcel before deploying your application.
React Hooks
React Hooks are functions that enable functional components to access React features such as state
and lifecycle methods. They were introduced in React 16.8 to provide a simpler and more flexible
way to write components and manage stateful logic without using class components.
Here are some of the most commonly used React Hooks:
1. useState:
useState allows functional components to manage state. It returns an array with the current
state value and a function to update the state.
Example:
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
2. useEffect:
useEffect enables functional components to perform side effects, such as data fetching,
subscriptions, or DOM manipulation, after every render.
Example:
useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
3. useContext:
useContext allows functional components to consume values from the React context. It
accepts a context object (created with React.createContext) and returns the current context
value.
Example:
return <div>{value}</div>;
};
4. useReducer:
useReducer is a hook that provides an alternative to useState. It accepts a reducer function
and an initial state, returning the current state and a dispatch function to update the state.
Example:
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<p>Doubled Count: {doubledCount}</p>
</div>
);
};
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(url);
const json = await response.json();
setData(json);
setLoading(false);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
}, [url]);
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
{/* Render data */}
</div>
);
};
3. Customize Parameters:
You can customize your custom Hook by accepting parameters. This allows you to make your
Hook more flexible and reusable in different scenarios.
Example:
useEffect(() => {
const interval = setInterval(() => {
setCount(prevCount => prevCount + step);
}, 1000);
return count;
}
By creating custom Hooks, you can encapsulate complex logic and share it across multiple
components, promoting code reuse and maintainability in your React applications. Custom Hooks are
a powerful feature of React that allows you to keep your components clean and focused on
presentation logic while moving the stateful and reusable logic into separate, reusable functions.