Publish to my blog (weekly)

    • This is why usually you’ll want to declare functions needed by an effect inside of it.
    • function doSomething() {  console.log(someProp); }
    • productId
    • productId
    • That makes it easy to see which props or state your effect uses, and to ensure they’re all declared:
    • The recommended fix is to move that function inside of your effect.
    • productId
    • productId
    • productId
    • the function is guaranteed to not reference any props or state, and also doesn’t need to be in the list of dependencies.
    • a pure computation
    • you can add a function to effect dependencies but wrap its definition into the useCallback Hook.
    • fetchProduct = useCallback
    • fetchProduct={fetchProduct}
    • fetchProduct
    • Note that in the above example we need to keep the function in the dependencies list. This ensures that a change in the productId prop of ProductPage automatically triggers a refetch in the ProductDetails component.

       

    • setCount(count + 1); // This effect depends on the `count` state
    • []); //
    • The empty set of dependencies, [], means that the effect will only run once when the component mounts, and not on every re-render.
    • Specifying [count] as a list of dependencies would fix the bug, but would cause the interval to be reset on every change.
    • each setInterval would get one chance to execute before being cleared (similar to a setTimeout.) That may not be desirable.
    • we can use the functional update form of setState. It lets us specify how the state needs to change without referencing the current state:
    • setCount(c => c + 1); // ✅ This doesn't depend on `count` variable outside
    • []); // ✅ Our effect doesn't use any variables in the component scope
    • the setInterval callback executes once a second, but each time the inner call to setCount can use an up-to-date value for count (called c in the callback here.)
    • Starting in React 18 with createRoot, all updates will be automatically batched, no matter where they originate from. This means that updates inside of timeouts, promises, native event handlers or any other event will batch the same way as updates inside of React events:
    • After React 18 updates inside of timeouts, promises,
    • native event handlers or any other event are batched.
    • The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.
    • useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:
    • return {...prevState, ...updatedValues};
    • Another option is useReducer, which is more suited for managing state objects that contain multiple sub-values.
    • If the initial state is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render:
    • () => {  const initialState = someExpensiveComputation(props);  return initialState; }
    • If you’re doing expensive calculations while rendering, you can optimize them with useMemo.

       

    • nstead, use useEffect. The function passed to useEffect will run after the render is committed to the screen.
    • By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.

       

    • effects create resources that need to be cleaned up before the component leaves the screen, such as a subscription or timer ID.
    • The clean-up function runs before the component is removed from the UI to prevent memory leaks
    • useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
    • If you use server rendering, keep in mind that neither useLayoutEffect nor useEffect can run until the JavaScript is downloaded. This is why React warns when a server-rendered component contains useLayoutEffect.
    • To exclude a component that needs layout effects from the server-rendered HTML, render it conditionally with showChild && <Child /> and defer showing it with useEffect(() => { setShowChild(true); }, []). This way, the UI doesn’t appear broken before hydration.
    • Building your own Hooks lets you extract component logic into reusable functions.
    • Traditionally in React, we’ve had two popular ways to share stateful logic between components: render props and higher-order components.
    • A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.
    • make sure to only call other Hooks unconditionally at the top level of your custom Hook.
    • Custom Hooks are a convention that naturally follows from the design of Hooks, rather than a React feature.
    • Without it, we wouldn’t be able to automatically check for violations of rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it.
    • Do two components using the same Hook share state? No. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.
    • Each call to a Hook gets isolated state. Because we call useFriendStatus directly, from React’s point of view our component just calls useState and useEffect.
    • We provide a linter plugin to enforce these rules automatically:

       

    • Instead, always use Hooks at the top level of your React function, before any early returns.
    • Don’t call Hooks inside loops, conditions, or nested functions.
    • Don’t call Hooks from regular JavaScript functions.
    • React function components.
    • custom Hooks
    • If we want to run an effect conditionally, we can put that condition inside our Hook:

Posted from Diigo. The rest of my favorite links are here.

댓글

이 블로그의 인기 게시물

Publish to my blog (weekly)

Publish to my blog (weekly)