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.
2. How do you use contextType?
ContextType is used to consume the context object. The contextType property can be used in two ways,
A) contextType as property of class:
The contextType property on a class can be assigned a Context object created by React.createContext().
After that, you can consume the nearest current value of that Context type using this.context in any of the lifecycle methods and render function.
Lets assign contextType property on MyClass as below,
b) Static field You can use a static class field to initialize your contextType using public class field syntax.
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.
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,