How can I pre initialise state with hooks in React?

Viewed 18046

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

4 Answers

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.

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
  },[])

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/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

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

Related