DEV Community

Cover image for 30 React One-Liners to Enhance Your Coding Efficiency
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

30 React One-Liners to Enhance Your Coding Efficiency

React is a powerful JavaScript library for building user interfaces. While its flexibility is one of its greatest strengths, it can sometimes lead to verbose code. Fortunately, there are many ways to simplify common patterns in React with concise, efficient one-liners. In this article, we will explore 30 useful React one-liners that will make your code cleaner and more efficient. Each example is accompanied by a brief explanation to highlight its usage.

1. Conditional Rendering

Simplify conditional UI rendering based on props or state.

const Greeting = ({ isLoggedIn }) => isLoggedIn ? <h1>Welcome!</h1> : <h1>Please log in</h1>;
Enter fullscreen mode Exit fullscreen mode

2. Default Props

Provide default values to props to avoid undefined errors.

const Button = ({ label = "Click Me" }) => <button>{label}</button>;
Enter fullscreen mode Exit fullscreen mode

3. Inline Styles

Apply dynamic styles directly using JavaScript objects.

const Box = ({ size }) => <div style={{ width: size, height: size, backgroundColor: 'blue' }} />;
Enter fullscreen mode Exit fullscreen mode

4. Functional Updates in State

Use functional updates to access the latest state.

const [count, setCount] = useState(0);
const increment = () => setCount(prev => prev + 1);
Enter fullscreen mode Exit fullscreen mode

5. Event Handling

Directly handle user input events inline.

const Input = () => <input onChange={e => console.log(e.target.value)} />;
Enter fullscreen mode Exit fullscreen mode

6. Spread Props

Pass all props to a component effortlessly.

const Button = props => <button {...props} />;
Enter fullscreen mode Exit fullscreen mode

7. Dynamic Classes

Dynamically assign CSS classes based on props.

const Alert = ({ type }) => <div className={`alert ${type}`}>Alert Message</div>;
Enter fullscreen mode Exit fullscreen mode

8. Array Mapping

Map over an array to generate a list of elements.

const List = ({ items }) => <ul>{items.map((item, index) => <li key={index}>{item}</li>)}</ul>;
Enter fullscreen mode Exit fullscreen mode

9. Array Filtering

Filter an array and render only the matching items.

const FilteredList = ({ items }) => <ul>{items.filter(item => item.active).map(item => <li key={item.id}>{item.name}</li>)}</ul>;
Enter fullscreen mode Exit fullscreen mode

10. Optional Chaining

Safely access deeply nested object properties.

const UserProfile = ({ user }) => <p>{user?.name || "Guest"}</p>;
Enter fullscreen mode Exit fullscreen mode

11. Short-Circuit Evaluation

Render components or elements conditionally.

const ErrorMessage = ({ error }) => error && <p>{error.message}</p>;
Enter fullscreen mode Exit fullscreen mode

12. Component as Prop

Pass components as props for reusable wrappers.

const Wrapper = ({ Component }) => <Component />;
Enter fullscreen mode Exit fullscreen mode

13. UseEffect with Dependency

Run effects only once during component mount.

useEffect(() => console.log("Mounted"), []);
Enter fullscreen mode Exit fullscreen mode

14. Debounced Input

Debounce user input to improve performance.

const Input = ({ onChange }) => <input onChange={e => debounce(onChange(e.target.value), 300)} />;
Enter fullscreen mode Exit fullscreen mode

15. Merging States

Merge new state updates into existing state.

const [state, setState] = useState({});
const updateState = updates => setState(prev => ({ ...prev, ...updates }));
Enter fullscreen mode Exit fullscreen mode

16. Destructured Props

Use destructured props for cleaner code.

const Greeting = ({ name }) => <h1>Hello, {name}</h1>;
Enter fullscreen mode Exit fullscreen mode

17. Memoized Callback

Memoize functions to avoid unnecessary re-creations.

const handleClick = useCallback(() => console.log("Clicked"), []);
Enter fullscreen mode Exit fullscreen mode

18. Custom Hook One-Liner

Create concise custom hooks for reusable logic.

const useToggle = initialValue => useState(initialValue).reduce((state, setState) => [state, () => setState(!state)]);
Enter fullscreen mode Exit fullscreen mode

19. Inline Fragment

Group multiple elements without adding extra DOM nodes.

const FragmentExample = () => <><p>First</p><p>Second</p></>;
Enter fullscreen mode Exit fullscreen mode

20. Context Consumer

Access context values using a consumer component.

const Theme = ({ ThemeContext }) => <ThemeContext.Consumer>{theme => <p>{theme}</p>}</ThemeContext.Consumer>;
Enter fullscreen mode Exit fullscreen mode

21. Default Function Props

Provide default functions as props to prevent runtime errors.

const Input = ({ onChange = () => {} }) => <input onChange={onChange} />;
Enter fullscreen mode Exit fullscreen mode

22. Prevent Default in Events

Prevent default behavior directly in event handlers.

const Link = ({ href }) => <a href={href} onClick={e => e.preventDefault()}>Click me</a>;
Enter fullscreen mode Exit fullscreen mode

23. Lazy Loaded Components

Dynamically import components for better performance.

const LazyComponent = React.lazy(() => import('./MyComponent'));
Enter fullscreen mode Exit fullscreen mode

24. Inline Error Boundary

Wrap children in a fallback UI for errors.

const SafeComponent = ({ children }) => <ErrorBoundary fallback={<p>Something went wrong</p>}>{children}</ErrorBoundary>;
Enter fullscreen mode Exit fullscreen mode

25. Render Props

Use the render-prop pattern for flexible components.

const DataFetcher = ({ render }) => {
  const [data, setData] = useState(null);
  useEffect(() => fetch('/api/data').then(res => res.json()).then(setData), []);
  return render(data);
};
Enter fullscreen mode Exit fullscreen mode

26. Conditional Attribute

Apply attributes conditionally based on logic.

const Button = ({ disabled }) => <button disabled={disabled || undefined}>Click</button>;
Enter fullscreen mode Exit fullscreen mode

27. Dynamic Imports

Dynamically load modules based on conditions.

const loadModule = condition => condition && import('./Module');
Enter fullscreen mode Exit fullscreen mode

28. Controlled Components

Synchronize input values with state easily.

const ControlledInput = ({ value, onChange }) => <input value={value} onChange={e => onChange(e.target.value)} />;
Enter fullscreen mode Exit fullscreen mode

29. Array Reduce for Rendering

Transform data into elements using reduce.

const List = ({ items }) => items.reduce((acc, item) => [...acc, <li key={item.id}>{item.name}</li>], []);
Enter fullscreen mode Exit fullscreen mode

30. Conditional Hooks

Use hooks conditionally without violating rules.

const useOptionalEffect = condition => condition && useEffect(() => console.log("Effect"), []);
Enter fullscreen mode Exit fullscreen mode

These one-liners demonstrate the elegance and versatility of React. By leveraging these concise patterns, you can write cleaner, more maintainable code that enhances productivity. Try incorporating them into your projects to see the difference!

Top comments (0)