Notes
Context
Don’t have single context for width and mobile beacuse when ever the width change the component that only using mobile (child2
) will also get re-render. this will applicable only if Child2
is Mounted to DOM
When should I use Context? - Any time you have some value that you want to make accessible to a portion of your React component tree, without passing that value down as props through each level of components.
Forward Ref and useImperativeHandle
Forward Ref are used pass ref from parent to child and useImperativeHandle is used to limit the ref functionality to the parent who passed or we can use this if we want to access child method on parent.
Tips And Tricks
-
Don’t return Null on a component which cause the component to unmount if you want mount again if it based on conditon use boolean it wil be not dispalayed in UI but will be avalible in V-DOM
-
Profiling Tips: When you do profiling using react profiler try make CPU 2x or some lower bound slow down to find the issue beacuse most of the modern system will do better and one more tips when looking the flame chart check for the single task duration that need to be less then ~16 milliseconds (
Human eyes are sensitive to motion, and frame rates below 60 fps may result in perceptible stuttering or flickering in animations
) if it taking more then 16 Milliseconds it will be laggy in UI -
useState for one-time initializations
const [resource] = React.useState(() => new Resource())
-
React chilldern will add key
React.Children.toArray(someData.map(item=><div>{item.title}</div>)
-
Toggle CSS instead of forcing a component to mount and unmount
-
Use virtualization for large lists
-
Whenever you have JSX repeating itself, extract the logic to a config object and loop through it.
UseRef
- use instead of useCallback
- Dont carry current destruct it
- Getter and setter in ref
Context
-
Not all the chilldern under context re-render the chillderen that consuming the value only re-render beacuse we used component composition here passed as chilldren
-
When we using useContext() in child component that will only get re-render
-
So always keep the useContext where it needed
- So use the context where it needed if use the context in Modal component it will be re-render on context change.
- Always try to pass the primitive data type to provider vaule or wrapp with memo because when the component above provider is changing which cause the Provider to re render and if we using no primitive data type like object which will change and react context will re-render all the chillderen when the vaule change
Patterns
Component composition
passing components as props to other components
Multiple components work together to achieve the functionality of a single entity.This will be usefull when we want props drilling we can use this patterns
Use this when we have parent component and that have 5 chillderen and we used to change the state of parent that not relvant for the chillderen wrap with composition
Refer : github
Render Prop
A render prop is a prop on a component, which value is a function that returns a JSX element. The component itself does not render anything besides the render prop. Instead, the component simply calls the render prop, instead of implementing its own rendering logic.
It is similar to higher order component
Higher order component
To share tracking logic across various UX components. if more one UI will have same function that need to share and UI is differ use this pattern
Convention need to follow
- A HOC should not change the API of a provided component
- HOCs should have a name following the
withNoun
pattern - HOCs should not have any parameters aside from the Component itself. HOCs can handle additional parameters via currying.
withNoun("some data")(MyComponent)
Compound Components
where a group of components works together to achieve a specific functionality. have
Rendering and Performance
Re-render reason
- State change
- Parent re-renders
- Context Provider changes (all components that use this Context will re-render)
- Hooks change (cause the re-render of the host component that using hooks)
Preventing Re-render
- Composition: moving state down
- Children as props
- React.Memo
- If Context Provider is placed not at the very root of the app, and there is a possibility it can re-render itself because of changes in its ancestors, its value should be memoized.
- Use State only the values that have effect on the vDOM. else use useRef
- Lift the state down as much possible to component that actually need
The mystery of React Element, children, parents and re-renders
-
if you pass children as a render function. (parent change will cause child re-render)
-
Wrapping parent with React.memo won’t protect the child of the parent
Memory leak
When using memoization techniques like useCallback
to avoid unnecessary re-renders, there are some things to watch out for. useCallback
will hold a reference to a function as long as the dependencies don’t change. Here’s an example:
- The first click on “Increment A” will cause
handleClickA()
to be recreated since we changecountA
- let’s call the new onehandleClickA()#1
. handleClickB()#0
will not get recreated sincecountB
didn’t change.- This means, however, that
handleClickB()#0
will still hold a reference to the previousAppScope#0
. - The new
handleClickA()#1
will hold a reference toAppScope#1
, which holds a reference tohandleClickB()#0
.
The general problem is that different useCallback
hooks in a single component might reference each other and other expensive data through the closure scopes. The closures are then held in memory until the useCallback
hooks are recreated. Having more than one useCallback
hook in a component makes it super hard to reason about what’s being held in memory and when it’s being released. The more callbacks you have, the more likely it is that you’ll encounter this issue.
Resources
- [React re-renders guide: everything, all at once](https://www.developerway.com/posts/react-re-renders-guide
- React Element, children, parents and re-renders
- When does React re-render components?
- https://reacthandbook.dev/react-performance-optimization
- Blogged Answers: A (Mostly) Complete Guide to React Rendering Behavior
- Performance using React Profiler
Patterns
- Component composition
- Component composition
- React components composition
- https://felixgerschau.com/react-component-composition/#how-can-composition-help-performance
- Effective Higher-Order Components
- https://kentcdodds.com/blog/optimize-react-re-renders
State Mangement
Simplifying React state management
- They use re select npm pkg for manipulating data from different store
Advanced
- https://medium.com/the-guild/under-the-hood-of-reacts-hooks-system-eb59638c9dba How hooks works under the hood
- https://stackoverflow.com/questions/53974865/how-do-react-hooks-determine-the-component-that-they-are-for
- https://webdeveloper.beehiiv.com/p/build-react-400-lines-code
- https://blog.frontend-almanac.com/JqtGelofzm1
Pkg
- State mangement like context but re-render only when actual val change
- A collection of modern, server-safe React hooks
Need to arrange
React clone element for component compositon
Do you need to calculate the state from a state or props you already have Do that in the component and not in useEffect
Do you update state in useEffect when a prop changes? Wrong !
Using useEffect to update state is wrong because the props are not a side effect. Instead you can derive the needed data from that prop and use it as it is in your JSX.
Never put any business logic into UI components. Extract all seState, useEffect to custom hook.
Use children props to stop re-rendering the children components
Understand identities when working with lists
Note: do not use Context for passing user actions between components Use composition or pass props
Don’t import SVGs as JSX or directly in React
Need to look
- https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/
- https://github.com/coryhouse/reactjsconsulting/issues/77
- https://molefrog.com/notes/react-tricks
- https://overreacted.io/a-chain-reaction/
Need to cover
- Forward ref
- useSyncExternalStore
Memory leak
- Avoid using usecallback if you have a big object or varible it will be hold on reference by the callback
- https://schiener.io/2024-03-03/react-closures
Internal of react 6hour
Tool