Reputation: 993
As we know, if we use a useState
in a Function Component
, state does not get created every time on re-renders
of that Function component, instead it uses existing state. See an Example
Function component below:
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Where as when we have a useState
in a customHook
instead (see below), each call to "useCustomHook
" makes a new state, which gives an idea that all custom hooks are just regular functions.
function useCustomHook() {
const [cnt, setCnt] = useState(0);
return [cnt, setCnt];
}
Upvotes: 1
Views: 246
Reputation: 31365
You can see from the snippet below, that a useState
call is persistent inside a customHook just like it works inside a regular component. You can keep track of it and even manipulate it. It's not recreated on every hook call.
Custom Hooks are a convention that naturally follows from the design of Hooks, rather than a React feature.
Do I have to name my custom Hooks starting with “use”?
Please do. This convention is very important. Without it, we wouldn’t be able to automatically check for violations of rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it.
Do two components using the same Hook share state?
No. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.
How does a custom Hook get isolated state?
Each call to a Hook gets isolated state. Because we call useFriendStatus directly, from React’s point of view our component just calls useState and useEffect. And as we learned earlier, we can call useState and useEffect many times in one component, and they will be completely independent.
function App(){
const [hookState,setHookState] = useSomeCustomHook();
function updateHookState() {
setHookState((prevState)=>prevState+1);
}
return(
<React.Fragment>
<div>Custom Hook State: {hookState}</div>
<button onClick={updateHookState}>Count</button>
</React.Fragment>
);
}
function useSomeCustomHook() {
const [hookState,setHookState] = React.useState(0);
return ([
hookState,
setHookState
]);
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 2