CodeBlanks Logo Icon CodeBlanks

Context and hooks

Set up data management with Context and custom hooks.

Sharing with Context

In this lesson we will open the tasks state to all components. Context carries data deep into the tree without prop drilling. We create a TasksContext and wrap App with TasksContext.Provider.

We give the Provider value={{ tasks, setTasks }}; this value becomes reachable in all child components. We write a useTasks hook to standardize reading the context: export function useTasks() { return useContext(TasksContext); }. This way each component accesses data with const { tasks } = useTasks(). This pattern is the foundation of medium and large apps.

The useTasks hook

useTasks is a custom hook that wraps useContext. You define it with export function useTasks() { return useContext(TasksContext); }. Each component calls this hook to access tasks and setTasks.

This pattern gives two advantages. First, every call site simplifies to one line: const { tasks } = useTasks(). Second, if you add a new field to the context value later, you only update the hook; every call site benefits automatically. Custom hooks break component logic into reusable pieces. That is why wrapping context with a hook is a good habit in intermediate projects.

Practice Wrap with Provider

Create a TasksContext with createContext(). Write a useTasks hook with useContext. Wrap App's return with <TasksContext.Provider value={{ tasks, setTasks }}>; put <Text>Tasks</Text> inside.

Starter code

App.js
import React, { useState, createContext, useContext } from 'react';
import { Text } from 'react-native';

// Create TasksContext with createContext

// Write the useTasks hook with useContext

function App() {
  const [tasks, setTasks] = useState([]);
  return <Text>Tasks</Text>;
}

Sample solution

App.js
import React, { useState, createContext, useContext } from "react";
import { Text } from "react-native";

const TasksContext = createContext();

export function useTasks() {
  return useContext(TasksContext);
}

function App() {
  const [tasks, setTasks] = useState([]);
  return (
    <TasksContext.Provider value={{ tasks, setTasks }}>
      <Text>Tasks</Text>
    </TasksContext.Provider>
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 createContext call

Question
const TasksContext = ____();
Answer
const TasksContext = createContext();

Explanation: createContext creates a new context.

2 What does the useTasks hook return?

App.js
const { tasks } = useTasks();
  • The context value Correct answer
  • A context
  • A state
  • An array

Explanation: useTasks returns the context value.

3 Match each piece to its role

Term Meaning
TasksContext Context definition
Provider Supplies the value
useTasks Reads the value
value Shared data

All lessons in Intermediate