A Consumer is a React component that subscribes to context changes. It requires a function as a child which receives current context value as argument and returns a react node.
The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree.
Lets take a simple example,
2. How do you solve performance corner cases while using context?
The context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider’s parent re-renders.
For example, the code below will re-render all consumers every time the Provider re-renders because a new object is always created for value.
This can be solved by lifting up the value to the parent state,
3. What is the purpose of forward ref in HOCs?
Refs will not get passed through because the ref is not a prop. It is handled differently by React just like a key. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component.
In this case, you can use Forward Ref API. For example, we can explicitly forward refs to the inner FancyButton component using the React.forwardRef API.
The below HOC logs all props,
Let's use this HOC to log all props that get passed to our “fancy button” component,
Now let's create a ref and pass it to FancyButton component. In this case, you can set focus to the button element.
That's all folks for today. Follow me @Shadabshs for more important and interesting updates related to web development
1. Is it ref argument available for all functions or class components?
Regular function or class components don’t receive the ref argument, and ref is not available in props either. The second ref argument only exists when you define a component with React.forwardRef call.
2. Why do you need additional care for component libraries while using forward refs?
When you start using forwardRef in a component library, you should treat it as a breaking change and release a new major version of your library.
1 . What is the purpose of default value in context?
The defaultValue argument is only used when a component does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them.
Below code snippet provides default theme value as Luna.