Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
How to manage state through Context and typescript

So I'm trying to learn how to use context since I'm building a dating app for dogs just as a fun project and will have to pass the current user throughout the whole application.

Tho i don't seem to grasp how to use context with typescript. I have a component called HomeView and would like to view counter and possibly set the counter with the usestate function setCounter.

When I try to log the counter in my HomeView components all I get is undefined even tho the value is set to 0. I should be able to log 0 onto the screen in my consumer. What am I missing?

Contex.tsx

import { createContext, useState } from 'react';

type ContextType = {
  setCounter: React.Dispatch<React.SetStateAction<number>>;
  counter: number;
};

export const CounterContext = createContext<ContextType>({} as ContextType);

export const CounterContextProvider: React.FC = ({ children }) => {
  const [counter, setCounter] = useState(0);

  return <CounterContext.Provider value={{ counter, setCounter }}>{children}</CounterContext.Provider>;
};

HomeView.tsx

export const HomeView = () => {
  const context = useContext(CounterContext);
  console.log(context.counter); // value is undefined

  return (
    <div className='signInWrapper'>
      <SignIn />
      <CounterContextProvider>
        {context.counter}  // Nothing is shown onto the screen
      </CounterContextProvider>
    </div>
  );
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Since you are retrieving the context in a component which is not nested in the CounterContext.Provider itself you are getting undefined.

You should nest your entire application in the CounterContextProvider in order to access the state globally.
You can do this in your App.js file:

function App() {
  return (
    <CounterContextProvider>
        ...
        <HomeView/>
    </CounterContextProvider>

After this you should be able to access the context in your HomeView component:

export const HomeView = () => {
  const { counter, setCounter } = useContext(CounterContext);

  return (
    <div className='signInWrapper'>
      <SignIn />
      Your counter value is: {counter}
    </div>
  );
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!