useContext Hook

  • use to retrieve value from context
  • easier to use than using Consumer component1
const TodoList = ({ todos }) => (
<ul>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}
</ul>
);
const TodoItem = ({ todo }) => {
const dispatch = useContext(TodoContext);
const handleChange = () =>
dispatch({
type: todo.complete ? 'UNDO_TODO' : 'DO_TODO',
id: todo.id,
});
return (
<li>
<label>
<input
type="checkbox"
checked={todo.complete}
onChange={handleChange}
/>
{todo.task}
</label>
</li>
);
};

Example using with Firebase

import React, { useContext } from 'react';
import { FirebaseContext } from '../components/Firebase'
const MessageFirebase = () => {
const firebase = useContext(FirebaseContext)
const db = firebase.firestore();
const sendMessage = (event) => {
event.preventDefault();
const message = event.target.elements.message.value;
db.collection('messages')
.add({
message: message,
})
.then((docRef) => {
console.log(`Message sent with ID: ${docRef.id}`);
})
.catch((error) => console.error(`Error adding message: ${error}`));
setMessage('');
};
// ...
}

Another Example2

const AppContext = React.createContext();
function NestedComponent() {
const appContext = useContext(AppContext);
return <p>{appContext}</p>;
}
function App() {
return (
<div className="App">
<AppContext.Provider value={"Hello from App šŸ‘‹"}>
<ChildComponent>
<GrandChild>
<NestedComponent />
</GrandChild>
</ChildComponent>
</AppContext.Provider>
</div>
);
}