Here's an updated version of the react_notes.mdx
file that includes additional React concepts and code examples:
# React Concepts and Code Examples
## Introduction to React
React is a JavaScript library for building user interfaces, developed by Facebook. It allows developers to create large web applications that can change data without reloading the page.
## Key Features of React
- **Component-Based Architecture**: Build encapsulated components that manage their own state.
- **Virtual DOM**: Efficiently updates and renders the right components when data changes.
- **Unidirectional Data Flow**: Data flows in a single direction, making it easier to understand and debug.
## Setting Up a React Project
To create a new React project, you can use Create React App:
```bash
npx create-react-app my-app
cd my-app
npm start
Basic React Component
A simple functional component in React:
import React from 'react';
const HelloWorld = () => {
return <h1>Hello, World!</h1>;
};
export default HelloWorld;
Class Components
React also supports class components:
import React, { Component } from 'react';
class HelloWorld extends Component {
render() {
return <h1>Hello, World!</h1>;
}
}
export default HelloWorld;
JSX
JSX is a syntax extension for JavaScript that looks similar to HTML.
const element = <h1>Hello, World!</h1>;
Props
Props are used to pass data from one component to another.
const Greeting = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};
// Usage
<Greeting name="Alice" />
State
State is a built-in object that stores property values that belong to a component.
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
Handling Events
React can handle events like click, change, etc.
const Button = () => {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
};
Conditional Rendering
You can render different components or elements based on conditions.
const Message = ({ isLoggedIn }) => {
return isLoggedIn ? <h1>Welcome Back!</h1> : <h1>Please Log In</h1>;
};
Lists and Keys
Rendering lists in React requires a unique key for each item.
const ItemList = ({ items }) => {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
Form Handling
React makes it easy to manage forms and handle user input.
const FormExample = () => {
const [inputValue, setInputValue] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Input: ${inputValue}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
};
Context API
The Context API allows you to manage global state and avoid prop drilling.
import React, { createContext, useContext, useState } from 'react';
const MyContext = createContext();
const ProviderComponent = ({ children }) => {
const [value, setValue] = useState('Hello');
return (
<MyContext.Provider value={{ value, setValue }}>
{children}
</MyContext.Provider>
);
};
const ChildComponent = () => {
const { value } = useContext(MyContext);
return <h1>{value}</h1>;
};
React Router
React Router is used for handling routing in a React application.
npm install react-router-dom
Basic routing setup:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const App = () => {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>
);
};
React Hooks
Hooks allow you to use state and other React features without writing a class.
useEffect
The useEffect
hook lets you perform side effects in your components.
import React, { useEffect } from 'react';
const Timer = () => {
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => clearInterval(timer); // Cleanup
}, []);
return <h1>Check the console for ticks!</h1>;
};
Custom Hooks
You can create custom hooks to encapsulate logic that can be reused across components.
import { useState, useEffect } from 'react';
const useFetchData = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then((response) => response.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
};
// Usage
const DataComponent = () => {
const { data, loading } = useFetchData('https://api.example.com/data');
if (loading) return <h1>Loading...</h1>;
return <div>{JSON.stringify(data)}</div>;
};
Error Boundaries
Error boundaries are a way to catch errors in React components.
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log('Error logged:', error);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
// Usage
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
Higher-Order Components (HOCs)
HOCs are functions that take a component and return a new component.
const withLoading = (WrappedComponent) => {
return ({ isLoading, ...props }) => {
if (isLoading) return <h1>Loading...</h1>;
return <WrappedComponent {...props} />;
};
};
// Usage
const MyComponent = () => <h1>Data Loaded!</h1>;
const MyComponentWithLoading = withLoading(MyComponent);
React Interview Questions
-
What is React? React is a JavaScript library for building user interfaces, developed by Facebook.
-
What are components in React? Components are the building blocks of a React application. They can be functional or class-based.
-
What is JSX? JSX is a syntax extension that allows you to write HTML-like code within JavaScript.
-
What are props? Props (short for properties) are used to pass data from one component to another.
-
What is state in React? State is an object that holds information about the component’s current situation.
-
What is the difference between state and props? State is local to a component and can change over time, while props are passed from parent to child components and are read-only.
-
What is the purpose of useEffect? The
useEffect
hook allows you to perform side effects in your components, such as fetching data or subscribing to events. -
What are React Hooks? Hooks are functions that let you use state and other React features without writing a class.
-
What is the Context API? The Context API is a way to manage global state in React and avoid prop drilling.
-
How do you handle forms in React? You can handle forms in React by managing input values with state and handling submission events.
-
What are Higher-Order Components? Higher-Order Components (HOCs) are functions that take a component and return a new component, allowing for code reuse.
-
What is the difference between a controlled and uncontrolled component? Controlled components have their form data controlled by React state, while uncontrolled components store their own state.
-
How do you optimize performance in React applications? Techniques include memoization, lazy loading components, using the React Profiler, and avoiding unnecessary re-renders.
-
What is the purpose of keys in lists? Keys help React identify which items have changed, are added, or are removed, improving performance during re-renders.
-
Explain the use of the
useReducer
hook. TheuseReducer
hook is used for managing complex state logic in React applications, providing a way to handle state transitions similar to Redux.