Key Takeaways from My Recent Review of the React Docs

jaamaalxyz

Md. Jamal Uddin

Posted on October 20, 2024

Key Takeaways from My Recent Review of the React Docs

This blog is originally posted on Medium

Hey there, fellow React enthusiasts! I've recently dived deep into the React documentation and want to share my learnings with you. This is a concise minimal guide for those who are looking to build a solid foundation in React. Let's break down the core concepts with simple explanations and code snippets.

This is going to be a somewhat lengthy story, but please hold on to grasp all the core concepts of React at once. You'll find it beneficial to recap and revisit these concepts for further advancement.

Table of Contents

Thinking in React

React is all about breaking your UI into reusable components. When building a React app, start by:

  1. Breaking the UI into a component hierarchy
  2. Building a static version with no interactivity
  3. Identifying the minimal representation of UI state
  4. Determining where your state should live
  5. Adding inverse data flow

Reference: https://react.dev/learn/thinking-in-react

Components and JSX

Components are the building blocks of React applications. They can be functional or class-based (old-fashioned, not recommended). JSX is a syntax extension that allows you to write HTML-like code in your JavaScript.

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

References:

Props

Props are how we pass data from parent to child components. They’re read-only and help keep our components pure.

function Greeting(props) {
  return <p>Welcome, {props.username}!</p>;
}

// Usage
<Greeting username="Alice" />
Enter fullscreen mode Exit fullscreen mode

Reference: https://react.dev/learn/passing-props-to-a-component

Conditional Rendering

React allows you to conditionally render components or elements based on certain conditions.

function UserGreeting(props) {
  return props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Reference: https://react.dev/learn/conditional-rendering

Rendering Lists

Use the map() function to render lists of elements in React. Don't forget to add a unique key prop to each item.

function FruitList(props) {
  const fruits = props.fruits;

  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit.id}>{fruit.name}</li>
      ))}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

Reference: https://react.dev/learn/rendering-lists

Pure Components

Pure components always render the same output for the same props and state. They’re predictable and easier to test.

function PureComponent(props) {
  return <div>{props.value}</div>;
}
Enter fullscreen mode Exit fullscreen mode

Reference: https://react.dev/learn/keeping-components-pure

UI Tree

React builds and maintains an internal representation of your UI called the virtual DOM. This allows React to efficiently update only the parts of the actual DOM that have changed.

Reference: https://react.dev/learn/understanding-your-ui-as-a-tree

Interactivity and Event Handlers

React uses synthetic events to handle user interactions consistently across different browsers.

function Button() {
  const handleClick = () => {
    alert('Button clicked!');
  };

  return <button onClick={handleClick}>Click me</button>;
}
Enter fullscreen mode Exit fullscreen mode

Reference: https://react.dev/learn/responding-to-events

State

State is used for data that changes over time in a component. Use the useState hook to add state to 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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Reference: https://react.dev/learn/state-a-components-memory

Controlled Components

Controlled components have their state controlled by React.

function ControlledInput() {
  const [value, setValue] = useState('');
  return <input value={value} onChange={e => setValue(e.target.value)} />;
}
Enter fullscreen mode Exit fullscreen mode

Uncontrolled Components

Uncontrolled components manage their state directly on the DOM.

function UncontrolledInput() {
  return <input defaultValue="Hello" />;
}
Enter fullscreen mode Exit fullscreen mode

Refs

Refs provide a way to access DOM nodes or React elements created in the render method.

import React, { useRef } from 'react';

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    inputEl.current.focus();
  };

  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Preventing Default Behavior

Use preventDefault() to stop the default browser behavior for certain events.

function Form() {
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Form submitted');
  };

  return <form onSubmit={handleSubmit}>...</form>;
}
Enter fullscreen mode Exit fullscreen mode

Event Propagation

React events propagate similarly to native DOM events. You can use stopPropagation() to prevent event bubbling.

function Parent() {
  return (
    <div onClick={() => console.log('Parent clicked')}>
      <Child />
    </div>
  );
}

function Child() {
  const handleClick = (e) => {
    e.stopPropagation();
    console.log('Child clicked');
  };

  return <button onClick={handleClick}>Click me</button>;
}
Enter fullscreen mode Exit fullscreen mode

Managing Complex States

Consider using the useReducer hook or a state management library like Redux or Zustand for complex state logic.

import React, { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Context

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

import React, { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Themed Button</button>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedButton />
    </ThemeContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

Reference: https://react.dev/learn/passing-data-deeply-with-context

Side Effects

Side effects are operations that affect something outside the scope of the function being executed, like data fetching or DOM manipulation. Use the useEffect hook to manage 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(result => setData(result));
  }, []); // Empty dependency array means this effect runs once on mount

  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}
Enter fullscreen mode Exit fullscreen mode

The best practices of useEffect

  1. Always include all variables on which your effect depends in the dependency array.
  2. Avoid infinite loops by carefully considering your effect’s dependencies.
  3. Clean up side effects in the return function of useEffect.
useEffect(() => {
  const subscription = props.source.subscribe();
  return () => {
    subscription.unsubscribe();
  };
}, [props.source]);
Enter fullscreen mode Exit fullscreen mode

References:

Rules of React

  1. Always start component names with a capital letter.
  2. Close all tags, including self-closing tags.
  3. Don’t modify props directly.
  4. Keep components pure when possible.

Reference: https://react.dev/reference/rules

Custom Hooks

Custom hooks allow you to extract component logic into reusable functions.

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}

// Usage
function MyComponent() {
  const width = useWindowWidth();
  return <div>Window width: {width}</div>;
}
Enter fullscreen mode Exit fullscreen mode

Rules of Hooks

  1. Only call hooks at the top level of your component.
  2. Only call hooks from React function components or custom hooks.
  3. Use eslint-plugin-react-hooks to enforce these rules.

Reference: https://react.dev/reference/rules/rules-of-hooks

That’s a wrap on our React journey! Remember, the best way to learn is by doing. Start building projects, experiment with these concepts, and don’t be afraid to dive into the React documentation when you need more details. Happy coding!

💖 💪 🙅 🚩
jaamaalxyz
Md. Jamal Uddin

Posted on October 20, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related