devmeetings-react-ts-fork
  • Devmeeting React + Typescript
  • Speed dating
  • Typescript
    • It's just JavaScript
    • Basic types
    • Typing objects
    • Typing functions
    • Modules
    • Generics
    • Tasks
  • Hello React
    • Quick look around
    • The first component
    • JSX
    • Tasks
  • Components & Props
    • Small components
    • Passing data to a component
    • Loops in JSX
    • Tasks
  • Stateful components
    • Handling events
    • Components with internal state
    • Talking to a parent component
    • Smart and dumb components
    • Before the break
    • Tasks
  • Side-effects and context
    • Side-effects
    • Prop drilling
    • Using context
    • Tasks
  • What's next
    • Styling
    • Learning component's lifecycle
    • State Management
Powered by GitBook
On this page
  • Creating context
  • Using the context
  • Providing values
  • Resources

Was this helpful?

  1. Side-effects and context

Using context

The context API is designed to contain data that is common for a number of components in the application. Data in top-level context can be considered global.

Creating context

The context object will be required to both write and read data in the context. It's best to have it in a separate file.

import React from "react";

export const MessageContext = React.createContext("Hello!")

The createContext method takes an optional default value and returns the context object that contains both the provider (write data) and consumer (read data) bits:

interface Context<T> {
    Provider: Provider<T>;
    Consumer: Consumer<T>;
    displayName?: string;
}

Using the context

The easiest way to use context is the useContext hook:

import React, { useContext } from "react";
import MessageContext from "./message-context";

const Message: React.FC = () => {
  const message = useContext(MessageContext);

  return <h1>{message}</h1>;
};

export default Message;

Given the Context object created earlier, the useContext hook returns the current context's value.

Providing values

The above code will work without any modifications - it will just show the default value provided when creating the context.

Using the Context.Provider component its possible to provide a different value:

import MessageContext from "./message-context";
import Message from "./Message";

function App() {
  return (
    <MessageContext.Provider value="Hello, Devmeetings">
      <Message />
    </MessageContext.Provider>
  );
}

Resources

PreviousProp drillingNextTasks

Last updated 5 years ago

Was this helpful?

Docs: Context
Docs: useContext hook
How the useContext Hook Works
Edit nervous-tharp-1eh3u