What is wrong in the following React code?

clock icon

Asked 1 year ago

message icon

1

eye icon

10

1function Counter() {
2 const [count, setCount] = useState();
3 return (
4 <button onClick={() => setCount(count + 1)}>
5 Clicked {count} times
6 </button>
7 );
8}
1function Counter() {
2 const [count, setCount] = useState();
3 return (
4 <button onClick={() => setCount(count + 1)}>
5 Clicked {count} times
6 </button>
7 );
8}

1 Answer

useState must be initialized with a value (e.g., 0).

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

Also, TypeScript users should provide a type.

1const [count, setCount] = useState<number>(0);
1const [count, setCount] = useState<number>(0);

1

Write your answer here

Top Questions