React Context | Data Layer
Data is the new oil.
Create child component for creating a similar type of sections in a page. Create a hide show collapsible accordion — send the data through child prop.
ui layer | data layer
What do we write to create ui layer? jsx
Who convert jsx? babel
What is jsx converts to? javascript objects
What is this big object structure known as? virtual dom.
What is the role of virtal dom? reconcilation
What is the diff between? new dom vs old dom
The whole ui layer is powered by data layer.
How the ui is rendered with data?
How data with in the application is maintained? states and props
What is the diff between state and props?
State are local variable and props are elements from one element to other element
Props drilling? Passing the props nestedly to multiple component. It is used to pass and reutilize the same data at multiple components.
Cons props drilling:
Passing the data in multiple components
Change in the one of the component can effect the code
Lifting the state up — create the state in parent component and pass to the child component by removing the state from the child component.
Other way is to use custom hooks for managing the data.
React dev tools — for debugging. React router dom is doing this.
Profilers tab in react dev tools shows exactly which component is taking more time and other stuffs such as for analysing the component
how to use context in react?
Create a context in a file
You can utilize context in each and every component
createContext — create the context
Context.Provider — update the context
useContext — to use the context value
const UserContext = createContext({
user: {
name: “Dummy Name”,
email: “dummy@gmail.com”
}
});
UserContext.displayName = “UserContext”;
export default UserContext;
— — — — -
Update the value
const [user, setUser] = useState()
<UserContext.Provider value={{ user, setUser }}>
<MyComponent />
</UserContext.Provider>
— — — -
Consume The context
const {user, setUser} = useContext(UserContext);
return (<>
<h1>{user}</h1>
<button onClick={e => setUser(e.target.value)} value={user}></button>
</>)