T.P.
T.P.

Reputation: 103

Using useState variable outside the function in reactJs

i have a function, in which i am using a useState hook on a variable named active. This variable takes a string value, and on click it takes the value of the category which is clicked on. My goal is to use this value of category outside the function in order to perform operations on that particular category.

Is there a way in which i can export the value which this active useState variable has, outside this function anywhere in the project.

the structure of my code is as follows:

export const funct = () => {

  // useState variable that will take the value of category that it gets clicked on/
  const [active, setActive] = useState('');


  return (
    <div className='abc'>
      {
        content.map((info) =>

           // Card is the category card which has a string value associated with, i.e. (info.name)

          <Card key={info.name} cardInfo={info} state={active} onClick={() => setActiveState(info.name)} />)

      }
    </div>
  )
}

any help would be appreciated. thank you

Upvotes: 0

Views: 2361

Answers (1)

Dave
Dave

Reputation: 7717

Depending on what you mean by "outside" the function there are generally 4 solutions.

  1. put the state higher in your application scope, and pass the getter/setter into the component.
  2. use React Context, wrap all components that need the shared state
  3. use a 3rd party library like redux or zustand
  4. roll your own "state outside of react" solution. i.e. Just stick a variable in global scope if you're not too concerned with concurrency, or use something like react-hooks-global-state or tips from this article or similar.

Upvotes: 1

Related Questions