How can I pre initialise state with hooks in React?

15,616

Solution 1

Here's the documentation: https://reactjs.org/docs/hooks-state.html

The example in the documentation shows:

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

The parameter passed in to useState (e.g. "0" in this case) is the initial value.

Solution 2

If you want to set initial state after loading data (fetch data from api) you can use "useEffect" in React hooks. it is equal to "componentWillReceiveProps" in class component. so when you set state value in useEffect make sure avoid infinity loop eg ..

const [count,setcount] = useState(0) 

 useEffect(()=>{
    setcount(api.data.count) // api.data.count from api after update store
  },[])

Solution 3

Here's an example of how state is initialized in classes vs functions with hooks:

Basically, the first argument of useState() is the initial state.

class CounterClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  
  render() {
    return <div>
      <strong>Class: </strong>
      <span>Count: {this.state.count}</span>&nbsp;
      <button onClick={() => this.setState({ 
        count: this.state.count + 1
      })}>Increase</button>
    </div>;
  }
}

function CounterFunction() {
  const [count, setCount] = React.useState(0); // Initial state here.
  return (
    <div>
      <strong>Function: </strong>
      <span>Count: {count}</span>&nbsp;
      <button onClick={() => 
        setCount(count + 1)}
      >Increase</button>
    </div>
  );
}

ReactDOM.render(
  <div>
    <CounterClass />
    <hr/>
    <CounterFunction />
  </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>

Solution 4

According React documentation you can pass your initial values to useState hooks.

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

https://reactjs.org/docs/hooks-reference.html#usestate

Share:
15,616
Hemadri Dasari
Author by

Hemadri Dasari

Founder @ www.letsdoretro.com Checkout Lets do retro Linkedin page. The Next generation collaborative retrospective tool. Where teams discuss what worked and what didn't. Together, online. Please do support by following our page. Checkout my Linkedin Profile

Updated on July 18, 2022

Comments

  • Hemadri Dasari
    Hemadri Dasari almost 2 years

    Basically in class components we pre initialise state in constructor with initial values like below.

         constructor(props){
              super(props);
              this.state = {
                     count: 0
              }
         }
    

    But after hooks are introduced all the class components became functional components with state.

    But my query is how can I pre initialise count state to 0 with hooks in React v16.7.0

  • Hemadri Dasari
    Hemadri Dasari over 5 years
    Ok what if I want to initialize some 20 different state variables? Do I need to use useState(0, “test”, 23, “male”, ..... so on); ?
  • Hemadri Dasari
    Hemadri Dasari over 5 years
    Ok what if I want to initialize some 20 different state variables? Do I need to use useState(0, “test”, 23, “male”, ..... so on); ?
  • Ryan Cogswell
    Ryan Cogswell over 5 years
    If you want them to be separate state variables, then you would call "useState" once for each variable (see the "Using Multiple State Variables" portion of the same documentation page). Alternatively you can have the state variable be an object with whatever structure you want (e.g. useState({ count: 0, gender: "male" }).
  • Omid Nikrah
    Omid Nikrah over 5 years
    You should declare that for each variable. reactjs.org/docs/…
  • Hemadri Dasari
    Hemadri Dasari over 5 years
    Thank you. Can you help me understand what if I have one more state string variable and I want to pre initialize this with initial value along with count. How can can I preinitialize more than one variable using useState?
  • Yangshun Tay
    Yangshun Tay over 5 years
    Yes you can have as many useState as you want within the component. If it's getting too many, you could use one useState and an object as the value. See this link for an example - codesandbox.io/s/vv8ypvp790 You could ask another question on SO and I can answer it there.