React, the popular JavaScript library for building user interfaces, continues to evolve with each passing year. In 2023, developers are relying on React more than ever to create efficient and maintainable web applications. To help you stay ahead in the ever-changing React landscape, we’ve compiled a list of the top 20 React code snippets, tips, tricks, and best practices. These code snippets cover a wide range of scenarios and will undoubtedly enhance your React development skills. Let’s dive in and discover the secrets of React success!
React Code Snippets
Conditional Rendering with if
Statement: This component conditionally renders content based on the isLoggedIn
prop. If isLoggedIn
is true
, it displays a welcome message; otherwise, it prompts the user to log in.
import React from 'react';
function ConditionalRendering({ isLoggedIn }) {
if (isLoggedIn) {
return <p>Welcome, user!</p>;
} else {
return <p>Please log in.</p>;
}
}
export default ConditionalRendering;
Mapping an Array to JSX Elements: The List
component takes an array of items
and maps them to <li>
elements. It’s important to provide a unique key
prop to each item to help React optimize rendering.
import React from 'react';
function List({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
export default List;
Handling Form Input with State: This component demonstrates how to create a controlled input field by using the useState
hook. It updates the inputValue
state as the user types.
import React, { useState } from 'react';
function InputForm() {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
};
return (
<input
type="text"
value={inputValue}
onChange={handleChange}
placeholder="Type something"
/>
);
}
export default InputForm;
Using useEffect
for Side Effects: The DataFetching
component uses useEffect
to fetch data from an API when the component mounts ([]
dependency array). It then updates the data
state and display it in a list.
import React, { useState, useEffect } from 'react';
function DataFetching() {
const [data, setData] = useState([]);
useEffect(() => {
// Fetch data from an API
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => setData(data));
}, []);
return (
<div>
<h1>Fetched Data:</h1>
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export default DataFetching;
Creating Reusable Components with Props: This snippet defines a reusable Greeting
component that takes a name
prop and displays a greeting message. You can use this component with different names.
import React from 'react';
function Greeting({ name }) {
return <p>Hello, {name}!</p>;
}
// Usage
<Greeting name="Alice" />;
Handling Click Events: This component uses state to keep track of a count and increments it when a button is clicked. The onClick
event handler updates the state.
import React, { useState } from 'react';
function ButtonCounter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
Conditional Rendering with Ternary Operator: This component conditionally renders a discount message based on the isDiscountAvailable
prop using a ternary operator.
import React from 'react';
function DiscountMessage({ isDiscountAvailable }) {
return (
<div>
{isDiscountAvailable ? (
<p>Get 10% off your purchase!</p>
) : (
<p>No discounts available.</p>
)}
</div>
);
}
Using useState
for Boolean State: This component toggles a button’s text and state using the useState
hook to manage boolean state (isToggled
).
import React, { useState } from 'react';
function ToggleButton() {
const [isToggled, setIsToggled] = useState(false);
const handleToggle = () => {
setIsToggled(!isToggled);
};
return (
<div>
<button onClick={handleToggle}>
{isToggled ? 'Toggle Off' : 'Toggle On'}
</button>
</div>
);
}
Passing Functions as Props:The ParentComponent
passes a function (handleClick
) as a prop to the ChildComponent
, allowing the child to trigger the function when a button is clicked.
import React from 'react';
function ParentComponent() {
const handleClick = () => {
alert('Button clicked!');
};
return <ChildComponent onClick={handleClick} />;
}
function ChildComponent({ onClick }) {
return <button onClick={onClick}>Click Me</button>;
}
Using React Fragments: React Fragments (<>
and </>
) allow you to group multiple elements without introducing an extra parent element in the DOM. Useful for cleaner markup and avoids unnecessary wrapper elements in the DOM
import React from 'react';
function FragmentDemo() {
return (
<>
<h1>Header</h1>
<p>Some content here.</p>
</>
);
}
💁 Check out our other articles😃
👉 Mastering Modern JavaScript: Your Comprehensive Cheat Sheet ES6- ES11
👉 Creating a Toggle Switcher with Happy and Sad Faces using HTML, CSS, and JavaScript
Handling Form Submissions: his component handles form submissions by capturing input changes with handleChange
, preventing the default form submission with handleSubmit
, and managing form data with state.
import React, { useState } from 'react';
function LoginForm() {
const [formData, setFormData] = useState({ email: '', password: '' });
const handleSubmit = (e) => {
e.preventDefault();
// Handle form submission with formData
};
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
/>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
placeholder="Password"
/>
<button type="submit">Submit</button>
</form>
);
}
Using React Context for State Management: This code demonstrates how to use React Context to pass data between components without the need for prop drilling. The ParentComponent
provides data through the context, and the ChildComponent
consumes it using useContext
.
import React, { createContext, useContext, useState } from 'react';
const MyContext = createContext();
function ParentComponent() {
const [data, setData] = useState('Initial data');
return (
<MyContext.Provider value={data}>
<ChildComponent />
</MyContext.Provider>
);
}
function ChildComponent() {
const data = useContext(MyContext);
return <p>Data from context: {data}</p>;
}
Conditional Rendering with Logical &&
Operator: The logical &&
operator can be used for simple conditional rendering. If showMessage
is true
, the message is displayed; otherwise, nothing is rendered.
import React from 'react';
function ShowMessage({ showMessage }) {
return showMessage && <p>This message is shown.</p>;
}
Mapping Object Keys to JSX: This component maps the keys of an object to JSX elements, creating a list of items with their corresponding values. Always provide a unique key
prop when rendering lists. This helps React efficiently update and reorder elements.
import React from 'react';
function RenderKeys({ data }) {
return (
<ul>
{Object.keys(data).map((key) => (
<li key={key}>{data[key]}</li>
))}
</ul>
);
}
Dynamic Styling with Inline Styles: Inline styles allow you to dynamically style components based on props or other conditions. In this example, the button’s background color is determined by the isPrimary
prop.
import React from 'react';
function StyledButton({ isPrimary }) {
const buttonStyle = {
backgroundColor: isPrimary ? 'blue' : 'gray',
color: 'white',
padding: '10px 20px',
borderRadius: '5px',
};
return <button style={buttonStyle}>Click Me</button>;
}
Using map
with Conditional Rendering: his component maps an array of items to list items but only renders those with isVisible
set to true
, allowing for conditional rendering within the map
function.
import React from 'react';
function RenderList({ items }) {
return (
<ul>
{items.map((item) => (
item.isVisible && <li key={item.id}>{item.text}</li>
))}
</ul>
);
}
Using useEffect
with Cleanup: This snippet uses useEffect
to start a timer when the component mounts and cleans it up when the component unmounts, preventing memory leaks.
import React, { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount((prevCount) => prevCount + 1);
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return <p>Count: {count}</p>;
}
Passing Props to Children: You can pass props to child components, including JSX elements, as shown in this example.
import React from 'react';
function ParentComponent() {
const message = "Hello from Parent!";
return (
<ChildComponent message={message}>
<p>This is a child element.</p>
</ChildComponent>
);
}
function ChildComponent({ message, children }) {
return (
<div>
<p>{message}</p>
{children}
</div>
);
}
Destructuring Props: Instead of accessing props directly, use destructuring to extract the props you need, which makes your code cleaner and more readable.
// Instead of this:
function MyComponent(props) {
return <div>{props.title}</div>;
// Use destructuring:
function MyComponent({ title }) {
return <div>{title}</div>;
}
Functional setState: When updating state that depends on the previous state, use the functional form of setState
. This ensures that state updates are batched correctly.
// Incorrect:
this.setState({ count: this.state.count + 1 });
// Correct (functional form):
this.setState((prevState) => ({ count: prevState.count + 1 }));
Conclusion
These 20 React code snippets, along with the associated tips, tricks, and best practices, will help you write clean, efficient, and maintainable code in 2023 and beyond. As you incorporate these techniques into your React development workflow, you’ll be better equipped to create exceptional user interfaces and deliver high-quality web applications. Happy coding!