Three options:

A. Send those functions as params and use curried functions:

const setPositionFactory = (setPositionAX, setPositionAY) => (pos = 200) => {
    setPositionAX(pos);
    setPositionAY(pos);
}

So you can call it inside your component in many ways:

Directly:
setPositionFactory(setPositionAX, setPositionAY)(); // default: 200
or Keeping the function for later use:
const setPosition = setPositionFactory(setPositionAX, setPositionAY);

// ...

setPosition(220);

B. Get those values as props of App and update state inside the component. It would be more idiomatic.

C. Use an Observable with rxjs and subscribe your component to it.

Adding observables to your question's code would be:

import { positionObs } from './observables';

const App () => {
    const [positionAX, setPositionAX] = useState(100);
    const [positionAY, setPositionAY] = useState(100);

    positionObs.subscribe((pos) => {
        setPositionAX(pos);
        setPositionAY(pos);
    });
}

Then in observables

import { Subject } from 'rxjs';

export const positionObs = new Subject();

export const setPosition = () => {
    positionObs.next(200);
};

Answer from Ignacio Lago on Stack Overflow
🌐
React
react.dev › reference › react › useState
useState – React
Call useState at the top level of your component to declare one or more state variables.
🌐
React Native
reactnative.dev › docs › state
State · React Native
February 20, 2026 - There are two types of data that control a component: props and state. props are set by the parent and they are fixed throughout the lifetime of a component. For data that is going to change, we have to use state.
Discussions

React Native - how to use 'useState()' in another function
This is not working. 2 things spring to mind. 1) Does it matter that this is React and Not react Native? - My example is Native and 2) I get the error can't find variable positionA - I am trying to set the position in a different function to the one I am calling it in. More on stackoverflow.com
🌐 stackoverflow.com
How to useState in react native? - Stack Overflow
It is also worth noting that useState is asynchronous and you could consider using: ... Alternatively, you could also try rendering the contents as well (although you've covered your bases above) with: ... And see if the text appears in the component. If it doesn't chances are the on callback isn't firing here. ... Sign up to request clarification or add additional context in comments. ... Yes, I tried in react native ... More on stackoverflow.com
🌐 stackoverflow.com
What is useState() in React?
You can also look in the source code to understand how useState is implemented. Here is the definition as of version 16.9. ... React hooks are a new way (still being developed) to access the core features of react such as state without having to use classes, in your example if you want to increment ... More on stackoverflow.com
🌐 stackoverflow.com
What problem does useState in React solve?
Great question and something that beginners struggle with more often, so no worries if it doesn’t make sense straightaway. In React, a component is nothing more but a regular function that returns JSX. A re-render is the function being called again, because something changes, for example when a prop has changed its value. Every expression in the component is re-run on each render. So a statement like ‘let count = 0’ will re-run when the component re-renders, meaning that if something triggers a re-render, the count variable will always be re-initiated to 0. This is not desirable in a lot of cases, which is why React exposes the useState API. useState ensures that whatever the value of a state variable is, that that value will be the same when the component re-renders. In addition to that, if you use the setter function of useState, not only do you change the value, you also trigger a re-render, because there might be other parts of the component relying on the state variable. Does this help? More on reddit.com
🌐 r/webdev
57
154
November 19, 2022
🌐
React
legacy.reactjs.org › docs › hooks-state.html
Using the State Hook – React
This is a way to “preserve” some values between the function calls — useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables ...
🌐
W3Schools
w3schools.com › react › react_usestate.asp
React useState Hook
The React useState Hook allows us to track state in a function component.
🌐
Medium
medium.com › geekculture › how-does-usestate-hook-works-react-native-example-c601e81a6611
How does useState() hook works(React Native Example)? | by Mohita Prakash | Geek Culture | Medium
January 22, 2022 - Due to this reason, React suggests calling them “function components”. useState is a function that accepts the initial state as an argument and returns a state value and a function to update this value.
Top answer
1 of 7
6

Three options:

A. Send those functions as params and use curried functions:

const setPositionFactory = (setPositionAX, setPositionAY) => (pos = 200) => {
    setPositionAX(pos);
    setPositionAY(pos);
}

So you can call it inside your component in many ways:

Directly:
setPositionFactory(setPositionAX, setPositionAY)(); // default: 200
or Keeping the function for later use:
const setPosition = setPositionFactory(setPositionAX, setPositionAY);

// ...

setPosition(220);

B. Get those values as props of App and update state inside the component. It would be more idiomatic.

C. Use an Observable with rxjs and subscribe your component to it.

Adding observables to your question's code would be:

import { positionObs } from './observables';

const App () => {
    const [positionAX, setPositionAX] = useState(100);
    const [positionAY, setPositionAY] = useState(100);

    positionObs.subscribe((pos) => {
        setPositionAX(pos);
        setPositionAY(pos);
    });
}

Then in observables

import { Subject } from 'rxjs';

export const positionObs = new Subject();

export const setPosition = () => {
    positionObs.next(200);
};

2 of 7
2

The state setters you get from useState are specific to the component instance, created when the component function is called the first time.

You have a few options:

  1. You can pass setPositionAX and setPositionAY into setPosition as arguments.

  2. You can put your setPosition function in your component function. (Yes, it'll be recreated each time, but that's fairly harmless.)

  3. You can create your own hook for position information.

#3 looks like this:

const usePosition = (_x = 0, _y = 0) => {
    const [x, setX] = useState(_x);
    const [y, setY] = useState(_y);
    const {current: setPosition} = useRef(function setPosition(_x = 0, _y = 0) {
        setX(x);
        setY(y);
    });

    return [x, y, setPosition];
};

Then in your component function:

const [xA, yA, setPositionA] = usePosition(0, 0);

// ...
setPositionA(200, 200);

Or if you prefer a tuple for the position information:

const usePosition = ([_x = 0, _y = 0] = []) => {
//                    ^^^^^^^^^^^^^^^ ^^^^^−− optional default value
//                     \             \
//                      +−−−−−−−−−−−−+−−−−−−− destructuring
    const [x, setX] = useState(_x);
    const [y, setY] = useState(_y);
    // (Ensure the setter is consistent across calls, like React does)
    const {current: setPosition} = useRef(function setPosition([_x = 0, _y = 0] = []) {
        setX(x);
        setY(y);
    });

    return [ [x, y], setPosition ];
};

Then in your component function:

const [positionA, setPositionA] = usePosition([0, 0]);
//                                            ^−−−−^−−−−− passing in a tuple

// ...
setPositionA([200, 200]);

Here's an example of that tuple version using React:

const { useState, useRef } = React;

const usePosition = ([_x = 0, _y = 0] = []) => {
    const [x, setX] = useState(_x);
    const [y, setY] = useState(_y);
    const {current: setPosition} = useRef(function setPosition([_x = 0, _y = 0] = []) {
        setX(x);
        setY(y);
    });

    return [ [x, y], setPosition ];
};

const Example = () => {
    const [positionA, setPositionA] = usePosition([0, 0]);
    const handleClick = () => {
        setPositionA([200, 200]);
    };
    
    return (
        <div>
            <div>Position: {positionA.join()}</div>
            <input type="button" onClick={handleClick} value="Set 200x200" />
        </div>
    );
};

ReactDOM.render(<Example/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

🌐
Stack Overflow
stackoverflow.com › questions › 65699321 › how-to-usestate-in-react-native
How to useState in react native? - Stack Overflow
Yes, that's because in your JS thread on React Native the state isn't updating before the end of the useEffect function, it's asynchronous. There's nothing further you need to do as the data is correctly appearing in your interface. Is there something else you wanted to do?
Find elsewhere
🌐
LogRocket
blog.logrocket.com › home › usestate in react: a complete guide
useState in React: A complete guide - LogRocket Blog
October 22, 2024 - React useState allows you to add state to functional components, returning an array with two values: current state and a function to update it.
🌐
GeeksforGeeks
geeksforgeeks.org › reactjs › reactjs-usestate-hook
React useState Hook - GeeksforGeeks
The useState() hook allows you to add state to functional components in React.
Published   January 10, 2026
Top answer
1 of 14
244

React hooks are a new way (still being developed) to access the core features of react such as state without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick prop, you could do something like:

...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...

const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};

and onClick:

<button onClick={setCount}>
    Click me
</button>

Let's quickly explain what is going on in this line:

const [count, setCounter] = useState(0);

useState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state. We can use the setCounter method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.

I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState, useEffect, useContext, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail.

update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.

2 of 14
78

useState is one of build-in react hooks available in 0.16.7 version.

useState should be used only inside functional components. useState is the way if we need an internal state and don't need to implement more complex logic such as lifecycle methods.

const [state, setState] = useState(initialState);

Returns a stateful value, and a function to update it.

During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).

The setState function is used to update the state. It accepts a new state value and enqueues a re-render of the component.

Please note that useState hook callback for updating the state behaves differently than components this.setState. To show you the difference I prepared two examples.

class UserInfoClass extends React.Component {
  state = { firstName: 'John', lastName: 'Doe' };
  
  render() {
    return <div>
      <p>userInfo: {JSON.stringify(this.state)}</p>
      <button onClick={() => this.setState({ 
        firstName: 'Jason'
      })}>Update name to Jason</button>
    </div>;
  }
}

// Please note that new object is created when setUserInfo callback is used
function UserInfoFunction() {
  const [userInfo, setUserInfo] = React.useState({ 
    firstName: 'John', lastName: 'Doe',
  });

  return (
    <div>
      <p>userInfo: {JSON.stringify(userInfo)}</p>
      <button onClick={() => setUserInfo({ firstName: 'Jason' })}>Update name to Jason</button>
    </div>
  );
}

ReactDOM.render(
  <div>
    <UserInfoClass />
    <UserInfoFunction />
  </div>
, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

New object is created when setUserInfo callback is used. Notice we lost lastName key value. To fixed that we could pass function inside useState.

setUserInfo(prevState => ({ ...prevState, firstName: 'Jason' })

See example:

// Please note that new object is created when setUserInfo callback is used
function UserInfoFunction() {
  const [userInfo, setUserInfo] = React.useState({ 
    firstName: 'John', lastName: 'Doe',
  });

  return (
    <div>
      <p>userInfo: {JSON.stringify(userInfo)}</p>
      <button onClick={() => setUserInfo(prevState => ({
        ...prevState, firstName: 'Jason' }))}>
        Update name to Jason
      </button>
    </div>
  );
}

ReactDOM.render(
    <UserInfoFunction />
, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

For more about useState see official documentation.

🌐
GeeksforGeeks
geeksforgeeks.org › what-is-usestate-in-react
What is useState() in React ? - GeeksforGeeks
January 9, 2025 - The useState() is a Hook that allows you to have state variables in functional components . so basically useState is the ability to encapsulate local state in a functional component.
🌐
Contentful
contentful.com › blog › react-usestate-hook
React useState hook: Complete guide and tutorial | Contentful
May 13, 2025 - The React useState hook adds a state variable to a function component. Setting a state variable gives your component the ability to remember things across page re-renders, so that data can be stored and the component can be updated when the ...
🌐
Hygraph
hygraph.com › blog › usestate-react
useState() Hook in React - A Complete Guide | Hygraph
January 21, 2026 - ... Allows us to obtain a state variable, this is a special variable that is capable of retaining data between renders. Provides us with a setter function to update the state variable and hence trigger a re-render of our component.
🌐
Reddit
reddit.com › r/webdev › what problem does usestate in react solve?
r/webdev on Reddit: What problem does useState in React solve?
November 19, 2022 -

Im not good in javascript and we started doing React in school.

Ive seen countless videoes on useState and read about it, but i dont get what problem its trying to solve. They all just say how to use it, not why to use it. It just seems like a variable with extra steps.

Like if i wanted to make a counter, i could:

const [count, setCount] = useState(0)

Now i have a variable, with an initial value, and which i can only update with a function (for some reason, why is that smart?).

Why wouldnt i just write:

Let count = 0

Shouldnt that suffice? I can add and subtract to that too, and i dont need a specific function to do so. When i refresh the page, both values resets regardless.

Top answer
1 of 21
479
Great question and something that beginners struggle with more often, so no worries if it doesn’t make sense straightaway. In React, a component is nothing more but a regular function that returns JSX. A re-render is the function being called again, because something changes, for example when a prop has changed its value. Every expression in the component is re-run on each render. So a statement like ‘let count = 0’ will re-run when the component re-renders, meaning that if something triggers a re-render, the count variable will always be re-initiated to 0. This is not desirable in a lot of cases, which is why React exposes the useState API. useState ensures that whatever the value of a state variable is, that that value will be the same when the component re-renders. In addition to that, if you use the setter function of useState, not only do you change the value, you also trigger a re-render, because there might be other parts of the component relying on the state variable. Does this help?
2 of 21
34
Here's a demonstration of the difference: https://playcode.io/1015207 There are 2 things that useState is used for in this context: Maintaining the state across re-renders Triggering a re-render You can see both of those in action in the example above. Function components are just functions, so if something triggers a re-render of your component and you've used a regular variable that's initialised in the function itself (e.g. by using let count = 0) then it will always be reset its initial value on re-render. The useState hook stores this state elsewhere, and so is able to ensure your state is retained correctly across re-renders. When the component is unmounted, the state is released. The action of updating a component's state also triggers a re-render in itself though. In function components, if you just update a variable somewhere or modify the DOM manually, etc. then React isn't aware of it, so won't update what's rendered. Again, you can see this in the example above, attempting to update the count variable doesn't trigger a re-render. You can also see in the example that if you click to increment count, and then click to increment the hook-based count that only the hook based count increases, showing the value for count must have been reset when the re-render was triggered.
Top answer
1 of 2
2
  1. You need to import useState and useEffect from React, not React Native
  2. You cannot call .then() on useEffect since it does not return a promise.
  3. You can't use useEffect as a callback function.

EDIT: Code example:

Based on the snippet from your question, it seems like you're trying to trigger a POST request to your database on submitting the text input. This can be achieved without useEffect by simply passing a handler function to your text input like so.

import React, { useEffect, useState } from 'react';
import { View, StyleSheet,TextInput } from 'react-native';
import db from 'D:/App development/PRLog/PrLogBeta/database/firestore'
const EnteryModal = props => {
    const [numReps,setNumReps] = useState('');
    
    const handleSubmit = async () => {
        try {
            await db.collection('Bench').add({reps:{newNum}});
            console.log('Number Added!');
        } catch (error) {
            console.log(error)
        }
    }

    return(
        <View style={styles.inputStyle}>
            <form>
                <TextInput
                    style = {styles.inputStyle}
                    keyboardType='number-pad'
                    placeholder={props.RepsOrWeight}
                    placeholderTextColor = 'white'
                    textAlign='center'
                    onChangeText={newNum => setNumReps(newNum)}
                    defaultValue={numReps}
                    onSubmitEditing={handleSubmit}
                >
                </TextInput>
            </form>
        </View>
    );
};

2 of 2
1

Use useState and useEffect as a react component not as react native component.

as shown in below example.

import React, { useEffect, useState } from 'react';
import { View, StyleSheet, TextInput} from 'react-native';
import db from 'D:/App development/PRLog/PrLogBeta/database/firestore'
const EnteryModal = props => {
const [numReps, setNumReps] = useState('');
  useEffect(() => {
  dataBaseCollection();
  console.log("Number Added!");
 }, []);
 const dataBaseCollection = () => {
 db.collection('Bench').add({ reps: { newNum } });
}
return (
<View style={styles.inputStyle}>
  <form>
    <TextInput
      style={styles.inputStyle}
      keyboardType='number-pad'
      placeholder={props.RepsOrWeight}
      placeholderTextColor='white'
      textAlign='center'
      onChangeText={newNum => setNumReps(newNum)}
      defaultValue={numReps}
      onSubmitEditing={(event) => {
        dataBaseCollection();
      }}
    >
    </TextInput>
  </form>
  </View>
 );
};
🌐
freeCodeCamp
freecodecamp.org › news › usestate-hook-3-different-examples
How to Use the useState() Hook in React – Explained with Code Examples
May 8, 2023 - You are going to create a login button that uses the useState() hook to render two different outcomes. One is a sign-in button with a message asking the user to sign in. The other is a button that, once the user is signed in, gives them the choice to sign out. import React from 'react' const Signin = () => { return ( <div> <div> <button type="button">Sign Out</button> <p>Welcome back, good to see you in here<p> </div> <div> <button type="button">Sign In</button> <p>Please Sign in</p> </div> </div> ) } export default Signin;
🌐
Medium
medium.com › @jbyj › okay-so-react-usestate-sucks-ef756cfce516
Okay, so React.useState Sucks
October 22, 2022 - React solves this by having a shared mutable global value that it assigns the relevant context data before calling the appropriate function to render the component (JS is single-threaded, so all synchronous in-order calls will reference the ‘right’ value during this process). The hook functions, like useState(), etc.
🌐
Reactnativedevelopmentcompany
reactnativedevelopmentcompany.co.uk › home › react native hooks explained: master usestate & useeffect
React Native Hooks Explained: Master useState and useEffect
June 12, 2025 - Imagine constructing a to-do list application or a counter app with just a sprinkle of code. This is the magic that useState brings to the table. It grants the ability to seamlessly integrate state variables into functional components, revolutionizing how we approach state management in React Native.
Price   $500
Address   2 Garrick Rd, NW9 6AA, London