how do I use state in tsx file that just has a default function

Viewed 818

I had create a new react native project by init a tabs (TypeScript) . this example has 2 tabs , each tab content in a tsx file that just have a single

export default function 

and how can I use sates in that function .

enter image description here

and how can I use sates in that function .

2 Answers

You can use state in a functional component as follows: (example taken from this link: https://reactjs.org/docs/hooks-intro.html)

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

To break this down,

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

basically means the same thing as

this.state = {
    count: 0; // 0 is what the count state variable initializes to
}

setCount(newStateCount) {
    count = newStateCount; // you change the state using setCount(1), for example. 
    // now count goes from 0 to 1 in this case.
}

React basically does the implementation of both for you in that single line, and all you have to do is call setCount in order to change the count state instead of this.state.count = newValue.

In response to the comment under this original answer: You can set state for multiple properties like so: how to write a multi lines state with Hooks useState in ReactJs

   const [state, setState] = useState({
        step: 1,
        firstName: '',
        lastName: '',
        jobTitle: '',
        jobCompany: '',
        jobLocation: '',
    });
   // Setting state like:
   setState(prev=>{...prev,firstName:'Joey'});

Using state in function components was made possible through React Hooks: https://reactjs.org/docs/hooks-intro.html

So, you can do something like this, with the useState hook:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Related