Hey guys, I am back, today I am going to talk about React.Context in reactjs.

If you are a reactjs developer, this simple tutorial is for you. It is not that hard to understand and it will help you to reuse the same code in all of your reactjs projects

Lets get into the matter, In one of my projects of toolny.com, I had to code for a react native application.

The idea was simple, the application should even work on complete offline mode. For this I used react watermelondb, the database is very fast and react.

There are more than double dozen screens in the app, where the user has to input fields so that, data will get saved into watermelondb and syncs to server later when internet is available.

The real problem that I faced was, how do I get the reference of the database in every screen possible, this is kind of what I needed.

I had one option of initializing database in App.js and passing down to the child elements, but that is very hard to maintain and difficult to scale. So we have gone for using React.Context, and it worked great and running successfully.

If you want to see the implementation quickly, click this github link.

This explanation should work for all databases and not just watermelondb(sqlite), as long as you are looking to get the reference of the database or any other variable of database, it should work fine.

Let’s start..

Create a folder in your project and call it db. And also create a file named DbProvider.js in db.

mkdir db
touch db/DbProvider.js

Now lets prepare Provider and and initialize database in DbProvider.js file.

If you are confused about what Providers and Consumers kindly read this blog post from official reactjs maintainers.

import React, { Component } from 'react'

import { Database } from '@nozbe/watermelondb'

import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite'

import schema from '../model/schema'

import User from '../model/User'

import migrations from '../model/migrations'

const adapter = new SQLiteAdapter({
  schema: schema,

  migrations
})

const database = new Database({
  adapter,

  modelClasses: [User],

  actionsEnabled: true
})

const DbContext = React.createContext('DEFAULT')

export default class DbProvider extends Component {
  render () {
    return (
      <DbContext.Provider value={database}>
        {this.props.children}
      </DbContext.Provider>
    )
  }
}

export { DbContext, DbProvider }

As you can see in the above code, we have created contex using createContext with default value of DEFAULT, we have used that created context to create a provider that is DbContext.Provider in the return statement with this.props.children which allows us to include future child components to reside in the DbContext.Provider.

Also look at the watermelondb database I have created, since this is not a watermelondb tutorial, I am ignoring that part. All you need to understand is the way I passed the database reference to DbContext.Provider.

Now open your App.js file and import the DbContext file. lets do that..

import React from 'react'

import { View, Text } from 'react-native'

import { DbProvider } from './db/DbProvider'

import Child from './Child'

const App: () => React$Node = () => {
  return (
    <DbProvider>
      <View>
        <Child />
      </View>
    </DbProvider>
  )
}

export default App

As you can see in the above code, I have surrounded Child component in the return statement with DbProvider. That’s it.

Provider part is over, lets code the receiver part i.e Child component which receives the database reference from the DbProvider.js.


import { ActivityIndicator } from 'react-native'

import React, { Component } from 'react'

import { View, StyleSheet, Text, Button } from 'react-native'

import { DbContext } from './db/DbProvider'

export default class Child extends Component {
  static contextType = DbContext

  componentDidMount () {
    console.log('Component Did Mount')

    const db = this.context

    console.log(db)
  }

  render () {
    return (
      <View>
        <Text>
          I am from child Component, I got database reference from App.js. Thank
          you
        </Text>
      </View>
    )
  }
}

Just import the DbContext from DbProvider.js file, thats it. Now we can access the database reference using DbContext.

Don’t forget to add contextType like below in your component which allows us to access database reference using this.context.

static contextType = DbContext

Now we should be able to access the database reference in all the Child components and also nested components of that.

I hope you followed my simple tutorial. If you have any doubts or clarifications, let me know in the comment section.

Refer to React.Context for more in depth understanding of React’s context.

Thank you.