Lately, I have been rereading the official React documentation during my commute. When I was just starting out, I studied React with my attention entirely on implementation. I wasn’t interested in how it worked or the direction React was pursuing. Now that I have built enough things, rereading the docs has made me realize how much I didn’t know. Everything from why React encourages declarative code to useful ways of using keys. It is helping me understand React on a deeper level.
Concurrent Session Support
https://velog.io/@siwol406/동시-접속-로그아웃에-관한-고민과-수정 This sprint, I needed to implement device limits and concurrent session support. Because it needed ongoing checks through fetching, I initially considered sockets, or fetching at an interval. Looking into it further, I discovered other approaches such as SSE.
Working Through the Official React Docs
React is a framework for expressing UI.
-
Returning JSX conditionally
- The drawback: duplicated code means changing className requires editing two places, making maintenance harder. → Let’s make it DRY (less repetitive).
if (isPacked) { return <li className="item">{name} ✅</li>; } return <li className="item">{name}</li>;- Ternary operator.
return <li className="item">{isPacked ? name + " ✅" : name}</li>; -
Managing state
-
Each component has independent state: giving a component state does not mean that state lives inside the component. State lives in React.
-
React preserves state while it renders the same component at the same position in the tree. When a component is removed or replaced with a different one, React discards that state.
-
To preserve state across rerenders, the tree structure must stay the same.
-
→ Therefore, do not nest component function definitions.
-
Conversely, what if I want to reset state at the same position?
-
Render components in different positions
{ isPlayerA && <Counter person="Taylor" />; } { !isPlayerA && <Counter person="Sarah" />; } -
Reset using a key: keys are not just for arrays. They are especially useful with forms.
(Keys are not globally unique. They specify positions only within their parent.)
- Using it on an img tag: you can give an
<img>tag akey. When it changes, React recreates the<img>DOM node. The image briefly flashes while loading, which is probably not something you want for every image in an app. But it makes sense when you want the image and its description to always match.
{isPlayerA ? ( <Counter key="Taylor" person="Taylor" /> ) : ( <Counter key="Sarah" person="Sarah" /> )} //form <ContactList contacts={contacts} selectedContact={to} onSelect={contact => setTo(contact)} /> <Chat key={to.id} contact={to} />Extra 3. Preserving the state of removed components
My thought: display: none, or lift state to the top.
- Use CSS: convenient for simple UI. It becomes very slow when there are many hidden trees.
- Lift state up: manage state in the parent component. The most common approach.
- Save it in local storage.
- Question: how can I stop the text from being rerendered?
import { useState } from "react"; // The best approach is to render it in the same position. export default function App() { const [showHint, setShowHint] = useState(false); const [text, setText] = useState(""); // Lift it up. return ( <div> {shoHint && ( <p> <i>Hint: Your favorite city?</i> </p> )} <Form /> <button onClick={() => { setShowHint(false); }} > Hide hint </button> </div> ); } function Form() { return ( <textarea value={text} onChange={(e) => setText(e.target.value)} /> ); } - Using it on an img tag: you can give an
-
-
State and reducers
- When state updates are spread across multiple event handlers, consolidate all the state update logic into one reducer function outside the component.
- This reduces the amount of code inside the component.
import { useState } from "react";
import AddTask from "./AddTask.js";
import TaskList from "./TaskList.js";
export default function TaskApp() {
const [tasks, setTasks] = useState(initialTasks);
function handleAddTask(text) {
setTasks([
...tasks,
{
id: nextId++,
text: text,
done: false,
},
]);
}
function handleChangeTask(task) {
setTasks(
tasks.map((t) => {
if (t.id === task.id) {
return task;
} else {
return t;
}
})
);
}
function handleDeleteTask(taskId) {
setTasks(tasks.filter((t) => t.id !== taskId));
}
return (
<>
<h1>Prague itinerary</h1>
<AddTask onAddTask={handleAddTask} />
<TaskList
tasks={tasks}
onChangeTask={handleChangeTask}
onDeleteTask={handleDeleteTask}
/>
</>
);
}
let nextId = 3;
const initialTasks = [
{ id: 0, text: "Visit Kafka Museum", done: true },
{ id: 1, text: "Watch a puppet show", done: false },
{ id: 2, text: "Lennon Wall pic", done: false },
];
-
The drawback: setTasks is called to update state. As the component grows, so does the amount of state logic. To reduce complexity and make it easier to work with, move this logic out of the component into a single function called a reducer.
-
Switch from setting state to passing actions to a dispatch function.
- Remove all the logic containing setTasks, and the add, change, and delete functions remain.
- Pass actions from event handlers to describe what the user did. The state update logic lives elsewhere. → Rather than setting tasks in the event handlers, pass actions to add, change, or delete tasks. (The user’s intent is clearly expressed.)
function handleAddTask(text) { dispatch({ // The action object should contain the minimum information about what happened. type: "added", // What happened is what matters. id: nextId++, text: text, }); } function handleChangeTask(task) { dispatch({ type: "changed", task: task, }); } function handleDeleteTask(taskId) { dispatch({ type: "deleted", id: taskId, }); } -
Write a reducer function.
- Because the reducer receives state (
tasks) as an argument, it can be declared outside the component. This reduces indentation and makes the code easier to read. - The convention is to use switch for readability.
function tasksReducer(tasks, action) { switch (action.type) { case "added": { return [ ...tasks, { // Return the next state. id: action.id, text: action.text, done: false, }, ]; } case "changed": { return tasks.map((t) => { if (t.id === action.task.id) { return action.task; } else { return t; } }); } case "deleted": { return tasks.filter((t) => t.id !== action.id); } default: { throw Error("Unknown action: " + action.type); } } } - Because the reducer receives state (
-
Use the reducer in the component.
- Replace useState with useReducer.
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
-
→ In the end, you only need to specify what happened. You don’t need to know how it happens.
useState vs useReducer
- Code size: useReducer helps reduce code when multiple event handlers update state in similar ways.
- Readability:
- Debugging: adding console logs to the reducer lets you see every update.
- Testing:
- Personal preference
If state-related bugs keep occurring, using a reducer is recommended.
Writing useReducer well
- Reducers must be pure.
- Write concisely with Immer. Use useImmerReducer to change state safely.
Passing data deeply with context
-
Problems with prop drilling
- Passing data deeply or sharing the same prop across many components can become verbose and inconvenient.
-
Using context
- Create a context
// Export it so components can use it. export const LevelContext = createContext(1); // The only argument is the default value.-
Use the context in components that need the data
export default function Heading({ children }) { const level = useContext(LevelContext); // ... } -
Provide context from the component that specifies the data
export default function Section({ level, children }) { return ( <section className="section"> <LevelContext.Provider value={level}>{children}</LevelContext.Provider> </section> ); }
Final version
import Heading from "./Heading.js";
import Section from "./Section.js";
export default function Page() {
return (
<Section level={1}>
<Heading>Title</Heading>
<Section level={2}>
<Heading>Heading</Heading>
<Heading>Heading</Heading>
<Heading>Heading</Heading>
<Section level={3}>
<Heading>Sub-heading</Heading>
<Heading>Sub-heading</Heading>
<Heading>Sub-heading</Heading>
<Section level={4}>
<Heading>Sub-sub-heading</Heading>
<Heading>Sub-sub-heading</Heading>
<Heading>Sub-sub-heading</Heading>
</Section>
</Section>
</Section>
</Section>
);
}
- Things to consider before using context
- Pass props
- Pass JSX as children
- Examples where context is useful
- Theming and dark mode
- The current account
- Routing
- State management
Scaling an app with reducers and context
https://velog.io/@superlipbalm/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior
A (Mostly) Complete Guide to React Rendering Behavior
Overview of the rendering process.
When JavaScript is compiled and prepared for deployment, JSX is converted into react.createElement() calls.
createElement: returns a React element, a plain JavaScript object describing the intended UI structure.
// This is JSX syntax.
return <MyComponent a={42} b="testing">Text here</MyComponent>
// It is transformed into the following call.
return React.createElement(MyComponent, {a: 42, b: "testing"}, "Text Here")
// Which produces an element object like this.
{type: MyComponent, props: {a: 42, b: "testing"}, children: ["Text Here"]}
Reconciliation: gathers render output across the component tree, compares it with the new object tree (virtual DOM), and collects a list of changes. It applies the calculated changes to the DOM in one synchronous sequence.
Render and commit phases
Render phase: render components and calculate changes.
Commit phase: apply the changes calculated during rendering to the DOM.
Then run componentDidMount, componentDidUpdate, and useLayoutEffect hooks synchronously.
Set a timeout,
and run useEffect hooks when it expires. Passive effects.
useTransition concurrent rendering: work can be paused during the render phase so the browser can handle events.
Rendering ≠ DOM updates: a component can render without any visible changes.