What is the basic knowledge of React?
Basic Knowledge of React
React is a powerful and popular JavaScript library developed by Facebook for building dynamic and interactive user interfaces, particularly for single-page applications. Understanding the foundational concepts of React is essential for anyone looking to develop modern web applications. Below is an overview of the basic knowledge areas in React:
1. What is React?
React is a frontend library focused on building user interfaces. It enables developers to create reusable UI components, manage the state of applications efficiently, and ensure that updates to the UI are performed optimally. React's declarative approach makes it easier to reason about your application and manage its state over time.
2. Components
Components are the building blocks of any React application. They allow you to split the UI into independent, reusable pieces that can be managed separately.
-
Functional Components: These are JavaScript functions that return JSX. They are simpler and easier to read.
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; }
-
Class Components: These are ES6 classes that extend
React.Component
and must contain arender()
method.class Greeting extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } }
3. JSX (JavaScript XML)
JSX is a syntax extension for JavaScript that resembles HTML. It allows you to write HTML-like code within JavaScript, making it easier to visualize the structure of your UI.
const element = <h1>Hello, world!</h1>;
Under the hood, JSX is transformed into React.createElement
calls, which React uses to construct the Virtual DOM.
4. Props (Properties)
Props are read-only inputs passed from parent to child components. They allow components to receive data and functions, enabling dynamic and reusable components.
function Welcome(props) { return <h1>Hello, {props.name}!</h1>; } // Usage <Welcome name="Alice" />
5. State
State is a way to manage data within a component that can change over time. Unlike props, state is mutable and is managed within the component.
-
Using
useState
Hook in Functional Components:import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }
-
Using
this.state
in Class Components:class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } render() { return ( <div> <p>You clicked {this.state.count} times</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button> </div> ); } }
6. Lifecycle Methods and Hooks
React provides lifecycle methods for class components and Hooks for functional components to handle side effects and manage component behavior during different phases of their lifecycle.
-
Class Component Lifecycle Methods:
componentDidMount()
: Called after the component is mounted.componentDidUpdate()
: Called after the component updates.componentWillUnmount()
: Called before the component is unmounted.
-
Hooks in Functional Components:
-
useEffect()
: Replaces lifecycle methods for handling side effects.import React, { useState, useEffect } from 'react'; function DataFetcher() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); // Empty array ensures this runs once on mount return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; }
-
7. Event Handling
React allows you to handle events such as clicks, form submissions, and more using event handlers.
function ToggleButton() { const [isOn, setIsOn] = useState(false); const handleClick = () => setIsOn(!isOn); return ( <button onClick={handleClick}> {isOn ? 'ON' : 'OFF'} </button> ); }
8. Conditional Rendering
React enables rendering components or elements conditionally based on the application's state or props.
function Greeting({ isLoggedIn }) { if (isLoggedIn) { return <h1>Welcome back!</h1>; } else { return <h1>Please sign up.</h1>; } }
9. Lists and Keys
Rendering lists of data in React requires using the map()
function and assigning unique keys to each list item for optimal performance and correct rendering.
function TodoList({ todos }) { return ( <ul> {todos.map(todo => ( <li key={todo.id}>{todo.text}</li> ))} </ul> ); }
10. Forms
Handling user input through forms is a common task in React. Controlled components are used to manage form data through component state.
function NameForm() { const [name, setName] = useState(''); const handleSubmit = event => { event.preventDefault(); alert('A name was submitted: ' + name); }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" value={name} onChange={e => setName(e.target.value)} /> </label> <input type="submit" value="Submit" /> </form> ); }
11. Styling
React offers multiple ways to style components, ensuring flexibility in design:
-
CSS Stylesheets: Import regular CSS files.
import './App.css'; function App() { return <div className="container">Hello World</div>; }
-
Inline Styles: Use the
style
attribute with JavaScript objects.function StyledDiv() { const divStyle = { color: 'blue', backgroundColor: 'lightgray', }; return <div style={divStyle}>Styled Div</div>; }
-
CSS-in-JS Libraries: Utilize libraries like Styled-Components or Emotion for scoped and dynamic styling.
import styled from 'styled-components'; const Button = styled.button` background-color: ${props => (props.primary ? 'blue' : 'gray')}; color: white; padding: 10px 20px; border: none; border-radius: 5px; `; function App() { return <Button primary>Click Me</Button>; }
12. Virtual DOM
React uses a Virtual DOM, a lightweight in-memory representation of the actual DOM. When the state of a component changes, React updates the Virtual DOM first, compares it with the previous version, and then efficiently updates only the parts of the real DOM that have changed. This process enhances performance by minimizing direct DOM manipulations, which are typically slow.
13. React Router
For building single-page applications with multiple views, React Router is commonly used to handle routing, enabling navigation between different components without reloading the page.
import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './Home'; import About from './About'; function App() { return ( <Router> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </Router> ); } export default App;
14. State Management Libraries
While React's built-in state management using Hooks is sufficient for many applications, larger projects may benefit from state management libraries like Redux, MobX, or Context API to manage complex state across multiple components.
// Example using Context API import React, { createContext, useState, useContext } from 'react'; const ThemeContext = createContext(); function ThemeProvider({ children }) { const [theme, setTheme] = useState('light'); return <ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>; } function ThemedComponent() { const { theme, setTheme } = useContext(ThemeContext); return ( <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}> <p>Current Theme: {theme}</p> <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Toggle Theme</button> </div> ); } function App() { return ( <ThemeProvider> <ThemedComponent /> </ThemeProvider> ); } export default App;
15. Best Practices
- Component Reusability: Build small, reusable components to promote maintainability and scalability.
- State Lifting: Move shared state to the closest common ancestor to manage data flow efficiently.
- Avoid Direct DOM Manipulation: Let React handle the DOM updates to maintain consistency and performance.
- Use Keys for Lists: Assign unique keys to list items to help React identify changes and optimize rendering.
- Optimize Performance: Utilize React's performance optimization techniques like
React.memo
,useMemo
, anduseCallback
to prevent unnecessary re-renders.
16. Getting Started with React
To begin developing with React, you can use Create React App, a CLI tool that sets up a new React project with a modern build setup.
- Install Node.js and NPM: Ensure you have Node.js and NPM installed on your machine.
- Create a New React App:
npx create-react-app my-app cd my-app npm start
- Explore the Project Structure: Familiarize yourself with the folders and files generated by Create React App.
- Start Building Components: Create and compose components to build your application's UI.
- Learn and Implement Hooks: Utilize Hooks like
useState
anduseEffect
to manage state and side effects within your components.
17. Conclusion
Having a solid grasp of the basic concepts of React is crucial for building effective and efficient web applications. By understanding components, JSX, props, state, Hooks, and best practices, developers can create dynamic and responsive user interfaces that enhance the overall user experience. As you delve deeper into React, exploring advanced topics like state management libraries, performance optimization, and server-side rendering will further empower you to build robust applications.
GET YOUR FREE
Coding Questions Catalog