React Native
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.
Exercise 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.
Show example solution
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>
);
}
Test yourself
-
createContext call
const TasksContext = ____();
Show answer
const TasksContext = createContext();
-
What does the useTasks hook return?
const { tasks } = useTasks();
- The context value
- A context
- A state
- An array
Show answer
The context value — useTasks returns the context value.
-
Match each piece to its role
- TasksContext
- Context definition
- Provider
- Supplies the value
- useTasks
- Reads the value
- value
- Shared data
Next lesson: API integration