- Context
- local storage
Context API:
When writing react application, we have to send data through props from one component to another, this is totally fine.
But sometimes there might be a data that needs to be accessed by all or many components, this might lead to problem of prop drilling
Prop drilling occurs when you need to pass down data through multiple nested components to reach the ones that require the data.
This would lead to components being tightly coupled with each other, to avoid this we use context.
how it works?
We need to use createContext() to create a new context.
It returns an object with a consumer and provider
const MyContext = createContext({});
console.log(MyContext);

The Provider component provides the state and the Consumer uses it.
Let’s make all our tasks available through context
First, let’s create a context and export it so we can use it in other component,
export const TaskContext = createContext([]);
Now, in our ToDo app we can use the provider component of TaskContext.provider and declare which values to put into context
<TaskContext.Provider value={{ tasks, setTasks }}>
<Task task={task} onDelete={deleteTask} onEdit={editTask} />
</TaskContext.Provider>
In the Task component, we have to use the useContext hook to get the values,
const { tasks } = useContext(TaskContext);
Nice, now the tasks are available to the task components also, thought this was unnecessarily and overkill for this.

This is the output!
LocalStorage
We can use local storage to store data on client side
Local storage is our browser storage in which we can store data as key value pairs without any expiration time.
React provides built in object localStorage for strightforward usage of it, to store a data we have to call setItem()
localStorage.setItem('tasks' , tasks);
To retrieve the data we can use getItem
const tasks = localStorage.getItem('tasks');
To remove the data we can use removeItem()
localStorage.removeItem('tasks');
We can use it in our react component like given below
useEffect(() => {
const localTasks = localStorage?.getItem("tasks");
if (!localTasks) {
return;
}
const parsedTasks = JSON.parse(localTasks);
setTasks(parsedTasks);
}, []);
useEffect(() => {
localStorage.setItem("tasks", JSON.stringify(tasks));
}, [tasks]);
Things to keep in mind when using local storage
- We should not store sensitive data in the localStorage, it is insecure
- Always handle cases when the data is not available in the browser
- Local storage has limited capacity
Leave a Reply