react useState example
Example 1: react usestate
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Example 2: prevstate in usestate
const [prevState, setState] = React.useState([]);
setState(prevState => [...prevState, 'somedata'] );
Example 3: state with react functions
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
Example 4: usestate in react
import React, { useState } from 'react';
function Example() {
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Example 5: simple usestate example
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
function LessText({ text, maxLength }) {
const [hidden, setHidden] = useState(true);
if (text.length <= maxLength) {
return <span>{text}</span>;
}
return (
<span>
{hidden ? `${text.substr(0, maxLength).trim()} ...` : text}
{hidden ? (
<a onClick={() => setHidden(false)}> read more</a>
) : (
<a onClick={() => setHidden(true)}> read less</a>
)}
</span>
);
}
ReactDOM.render(
<LessText
text={`Focused, hard work is the real key
to success. Keep your eyes on the goal,
and just keep taking the next step
towards completing it.`}
maxLength={35}
/>,
document.querySelector('#root')
);
Example 6: usestate in react
The initial value will be assigned only on the initial render (if it’s a function, it will be executed only on the initial render).