Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pre initialise state with hooks in React?

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

like image 895
Hemadri Dasari Avatar asked Nov 08 '18 19:11

Hemadri Dasari


2 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.

like image 110
Ryan Cogswell Avatar answered Sep 28 '22 04:09

Ryan Cogswell


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
  },[])
like image 21
Damith Asanka Avatar answered Sep 28 '22 05:09

Damith Asanka