React Native Context API Tutorial | React State Management Tutorial For Beginners

 

Welcome folks today in this blog post we will be talking about react new native context api and also how to handlle state of your react applications. All the source code which is used in this tutorial is given below. A step by step youtube video is also shown below.

 

 

 

 

What is React Context API

 

The new React context api which is introduced recently has many advantages when it comes to passing data back and forth among components inside react application. It is similar to REDUX another popular state management library. But the react context api is built in react. No external dependency is required to use context api.

 

Get Started

 

In order to get started you need to create a react project and inside your main app.js file write this code which is shown below.

 

import React,{Component} from "react";

export default class App extends Component{
  state = {
    name:"India"
  }
  render(){
    return(
      <div>
        hello world
        <Person name={this.state.name}/>
        </div>
    )
  }
}

 

Here we are using the traditional way of passing data inside react components which is through props or properties. This is standard way when there are less components. This is exactly that we are doing here. We have the base component App and here we have one property inside the state which is country and here we are passing through props. And we have a custom component Person and we are passing this through props

 

class Person extends Component{
  render(){
    return(
      <div>
        <Country name={this.props.name}/>
        </div>
    )
  }
}

 

See also  React.js Hooks Maths Mini Scientific Calculator Deployed to Github Hosting Using Javascript Full Project For Beginners

 

And now inside it again we have another component where we are passing the received data from the parent component. The conclusion that we can draw here there is no direct path so that we can pass data directly to the component that we want to send. We want to pass data to all the components until we reach the desired component in this case it is the country component.

 

 

const Country = (props) => (
  <div>
    <p>The Country name is {props.name}</p>
    </div>
)

 

 

Concept of Context API

 

At this moment of time we will introduce react context api to counter the problems that we are facing to trasnfer the state of the application. Here we will creating the context.

 

// first we will make a new context
const MyContext = React.createContext();

// Then create a provider Component
class MyProvider extends Component {
  state = {
    name: 'Wes',
    age: 100,
    cool: true
  }
  render() {
    return (
      <MyContext.Provider value={{
        state: this.state,
        growAYearOlder: () => this.setState({
          age: this.state.age + 1
        })
      }}>
        {this.props.children}
      </MyContext.Provider>
    )
  }
}

 

 

Here we have created the global state and transferred to the context class that we have created i.e. MyProvider so in this we have stored our state of the application

See also  React.js Redux Tic Tac Toe Computer AI Single or Multiplayer Board Game Deployed to Vercel in Javascript Full Project For Beginners

Now we have a consumer to consume this data which is there inside the provider class that we have created.

 

class Person extends Component {
  render() {
    return (
      <div className="person">
        <MyContext.Consumer>
          {(context) => (
            <React.Fragment>
              <p>Age: {context.state.age}</p>
              <p>Name: {context.state.name}</p>
              <button onClick={context.growAYearOlder}>🍰🍥🎂</button>
            </React.Fragment>
          )}
        </MyContext.Consumer>
      </div>
    )
  }
}

 

 

Full App.js

 

import React, { Component } from 'react';

// first we will make a new context
const MyContext = React.createContext();

// Then create a provider Component
class MyProvider extends Component {
  state = {
    name: 'Wes',
    age: 100,
    cool: true
  }
  render() {
    return (
      <MyContext.Provider value={{
        state: this.state,
        growAYearOlder: () => this.setState({
          age: this.state.age + 1
        })
      }}>
        {this.props.children}
      </MyContext.Provider>
    )
  }
}

const Family = (props) => (
  <div className="family">
    <Person />
  </div>
)

class Person extends Component {
  render() {
    return (
      <div className="person">
        <MyContext.Consumer>
          {(context) => (
            <React.Fragment>
              <p>Age: {context.state.age}</p>
              <p>Name: {context.state.name}</p>
              <button onClick={context.growAYearOlder}>🍰🍥🎂</button>
            </React.Fragment>
          )}
        </MyContext.Consumer>
      </div>
    )
  }
}


class App extends Component {
  render() {
    return (
      <MyProvider>
        <div>
          <p>I am the app</p>
          <Family />
        </div>
      </MyProvider>
    );
  }
}


export default App;

 

 

 

 

Leave a Reply