How to use React Context: Difference between react and context

How to use React Context: Difference between react and context

How to use React Context

React Context is a technique for passing properties from the parent component to the child component(s) without manually passing the properties at each level of the component tree. The properties are stored in a store (similar to Redux) and used by the child component(s) from the store.

Knowing this, You must also be aware that React provides one-way data binding means you can send data only from parents to children through props. But sending data from children to parents or sending data in sibling components becomes a little complicated, especially for more extensive applications.

React context solves this problem. It allows us to easily share the data across our segments without using props.

It is a state management tool with a central store containing all the states. You can quickly create, update or delete those states and consume forms in your component.

Context API was introduced in react 16.3. It is a way to effectively produce global variables that can be passed around in reaction. Context is a more accessible and lighter state management tool compared to redux. It is also inbuilt with the functionality of reacting using react hooks.

When to use React Context: 

There are other ways to manage our react state, like redux, mobX, recoil, zustand, etc. But in these packages, respond context (built-in react ) and redux are the most popular.
Redux:

  • Redux is a state management tool similar to the context API. To use redux, we have to install a package which is a cross-platform open-source javascript library that helps to manage the state of each component of your application. It provides a centralized place to write all our state logic inside reducers. 
  • It was launched in June 2015.
  • Redux is an independent library on any UI. It can be used with any UI framework or library.
  • But in general, we use context API for smaller applications, and we use redux for large applications with many components. Because it provides a powerful redux toolkit that helps us debug the code and is performance optimized, below are some differences between context API and redux: 

Context API

Redux

It is built in react. We don’t have to install any extra library. For redux, we need to install a different library. Because of that, the size of our bundle application increased slightly.
It comes with react when we create – react – app, so it requires minimal setup to start work. Integrating this library to work with the react applications requires more configuration.
It is mainly designed for static data, which do not often change or update. It works perfectly with both static type and dynamic type data.
If we want to add a new context, we must create it from scratch. In redux, we can easily extend it because adding new data or action is easy once we do the initial setup.
Debugging react context could be hard in a highly nested application with a large code base. Even though we are doing it with Dev, Tool. Redux provides a powerful redux tool kit that provides an easy way to debug code.
In react context, the UI and state management logic are in. the same component. It provides a better code organization where we write separately our UI logic and state management logic

 

API: 

  • React.createContext ( )

const MyContext = React.createContext(defaultValue);

a Context object is created. The closest matching Provider above it in the tree will read the current context value when React renders a component subscribing to this Context object.

Only when a component lacks a matching Provider above it in the hierarchy is the defaultValue parameter used. This default setting can be advantageous for testing components without packaging them separately. It should be noted that consuming components do not use defaultValue when undefined is supplied as a Provider value.

  • Context.Provider:

<MyContext.Provider value={/* some value */}>

Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes.

The consuming components that are this Provider’s descendants can get a value prop from the Provider component. Many consumers can be connected to one provider. To override values farther down the tree, providers can be nested.

Every time a Provider’s value proposition changes, all customers who are descendants of that Provider will re-render. The shouldComponentUpdate function does not apply to the propagation from the Provider to its descendant consumers, including.contextType and useContext. Thus the consumer is updated even if an ancestor component skips an update.

The modifications are obtained using the same algorithm as the Object. to compare the old and new values.

  • Class.contextType

A Context object made by React can be applied to the contextType property on a class. createContext(). This property enables you to use this. Context to consume the closest available current value of that Context type. Any lifecycle method, including the render function, may refer to this. Use the same algorithm as Object. to compare the old and new values.

  • Context. consumer :

<MyContext.Consumer>

  {value => /* render something based on the context value */}

</MyContext.Consumer>

A React component that is context-sensitive. You can subscribe to a context inside a function component using this component.

It needs to serve a child-related purpose. The function returns a React node after receiving the current context value. The closest Provider for this context above in the tree’s value prop will be used as the value argument passed to the function. The value argument will be equal to the defaultValue that was supplied to createContext if there is no Provider for the context, as mentioned earlier.

  • Context.displayName:

There is a displayName string property available on the context object. React DevTools use this string to decide what to display for the context.

How to use Context API: 

  1. Create a folder in your root directory and give names as contexts ( just a convention);
  2. Under that folder, create all context files like userContext.js, productContext.js, countContext.js, etc.
  3. We will do 2 things in the context file:
  • Create Context: 

import React, { createContext } from ‘react’;

const UserContext = createContext();

  • Create a component like userProvider, productProvider, etc.

const UserProvider = ({ children }) => {

  const [name, setName] = useState(“Chris”);

  const [age, setAge] = useState(15);

  const increaseAge = () => setAge(age + 1);

  return (

    <UserContext.Provider value={{ name, age, increaseAge }}>

      {children}

    </UserContext.Provider>

  );

};

  • Export those functions: 

export { UserProvider };

export { ProductUser };

  • Import provider in index.js file and pass them

ReactDOM.render(

  <UserProvider>

    <App />

  </UserProvider>,

  document.getElementById(“root”)

 

CONCLUSION:

I hope this article was helpful and gave you deep insight into React context, the uses of Context API, and a well-explained difference between React and context API.

Summary
Article Name
How to use React Context: Difference between react and context
Description
React Context is a technique for passing properties from the parent to the child component(s) without passing the properties at each level of the component tree
Author
Publisher Name
BugendaiTech Pvt Ltd
Publisher Logo
Spread the updates

Leave a reply



Notice: Undefined index: position_on_screen in /home/tl2jq5v7asif/public_html/wp-content/plugins/mystickyelements/mystickyelements-front.php on line 203