$ npm install zustand
createconst useStore = create<Store>((set) => ({
address: '',
setAddress: (address: string) => set((state) => ({ ...state, address }))
}));
‼️주의
const [address, setAddress] = useState(String)('');
interface Store {
address: string;
setAddress: (address: string) => void;
}
const { 상태,...,상태변경함수 ,.... } = useStore훅함수();
const { address, setAddress } = useStore ();
export default function Zustand() {
const { address, setAddress } = useStore ();
// const onChange = (event:ChangeEvent<HTMLInputElement>) => {
// const { value } = event.target;
// setAddress(value);
// }
return (
<div style={{padding:'40px', height:'400px', backgroundColor:'gray'}}>
{/* <h1>{address}</h1>
<input value={address} onChange={onChange} /> */}
<Subcomponent1/>
<Subcomponent2/>
</div>
)
}
서브컴포넌트를 통한 다수의 컴포넌트 상태관리
function Subcomponent1(){
return(
<div style={{margin:'40px',height:'130px', backgroundColor:'red'}}>
<h1>안녕</h1>
<Sub2Component1/>
</div>
)
}
function Subcomponent2(){
return(
<div style={{margin:'40px',height:'130px', backgroundColor:'red'}}>
<Sub2Component2/>
</div>
)
}
function Sub2Component1(){
const {address} =useStore();
return(
<div style={{height:'75px', backgroundColor:'blue'}}>
<h3 style={{color:'yellow'}}>{address}</h3>
</div>
)
}
function Sub2Component2(){
const {address,setAddress} =useStore();
const onChange = (event:ChangeEvent<HTMLInputElement>) =>{
const {value} = event.target;
setAddress(value);
}
return(
<div style={{height:'75px', backgroundColor:'blue'}}>
<h3 style={{color:'yellow'}}>{address}</h3>
<input value={address} onChange={onChange} type="text" />
</div>
)
}