UseState Hooks in react gatsby

Viewed 2053
import React, {useState} from 'react'
import Layout from "../components/layout"

const blog = () => {
    const [state, setState] = useState({
        name: 'Kerry',
        age: 20
    });
    return (
        <Layout>
        <div>
            <h1>blog</h1>
            <p>Post will show up here later on</p>
            {state.name + state.age}
            
        </div>
        </Layout>
    )
}

export default blog

Hi I am trying to print out name from state. I am using react hooks. This project is built in gatsby command. From my understanding the line {state.name + state.age} should return my name and age.

but the programs terminal is returning rebuilding failed

Also The program is giving me 2 error.

here theses two

5:19  warning  'setState' is assigned a value but never used no-unused-vars

 5:31  error    React Hook "useState" is called in function "blog" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

So a, i using useState wrong

1 Answers

Components must start with capital letters. You have to change blog to Blog. The rest of the code seems correct.

This is because if they start with a lowercase letter, it is interpreted as a built-in component such as <p> or <img> by React. Since they are passed to React.createElement it breaks your code.

You can check for further information in React's official documentation.

Related