Reputation:
I have a component X it accepts Y from props. Is it possible to use Y in hooks?cod
import React, { useState } from "react";
function X({ y }) {
const [index, setIndex] = useState(y);
const ADD = () => {
setIndex(index + 1);
};
return (
<div>
{index}
<button onClick={ADD}>+</button>
</div>
);
}
Upvotes: 1
Views: 5256
Reputation: 112777
Using a prop as argument to useState
works great for setting an initial value.
Example
const { useState } = React;
function X({ y }) {
const [index, setIndex] = useState(y);
const add = () => {
setIndex(index + 1);
};
return (
<div>
{index}
<button onClick={add}>+</button>
</div>
);
}
ReactDOM.render(<X y={5} />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
Upvotes: 4