usecontext hook code example
Example 1: usecontext hook
import React, { useContext } from "react";
import ColorContext from "./colorcontex.ts";
const MyComponent = () => {
const colors = useContext(ColorContext);
return ...
;
};import React, { useContext } from "react";
const MyComponent = () => {
const colors = useContext(ColorContext);
return ...
;
};
Example 2: usereducer hook
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
>
);
}